C++ 为什么decltype(auto)不能按预期工作? #包括 #包括 int main() { 自动f1=[](自动和e)->自动 { 返回e; }; 自动f2=[](自动和e)->自动& { 返回e; }; 自动f3=[](自动和&e)->自动&& { 返回e; }; 自动f4=[](自动和&e)->数据类型(自动) { 返回e; }; int n{}; f1(标准::移动(n));//确定 f2(标准::移动(n));//确定 f3(标准::移动(n));//确定 f4(标准::移动(n));//错误 }
clang的错误消息: 错误:对类型“int”的右值引用无法绑定到类型“int”的左值 对我来说,C++ 为什么decltype(auto)不能按预期工作? #包括 #包括 int main() { 自动f1=[](自动和e)->自动 { 返回e; }; 自动f2=[](自动和e)->自动& { 返回e; }; 自动f3=[](自动和&e)->自动&& { 返回e; }; 自动f4=[](自动和&e)->数据类型(自动) { 返回e; }; int n{}; f1(标准::移动(n));//确定 f2(标准::移动(n));//确定 f3(标准::移动(n));//确定 f4(标准::移动(n));//错误 },c++,lambda,c++14,decltype,type-deduction,C++,Lambda,C++14,Decltype,Type Deduction,clang的错误消息: 错误:对类型“int”的右值引用无法绑定到类型“int”的左值 对我来说,decltype(auto)只有三种可能的推断类型: auto auto& auto& 为什么f4错误,而其他三个都正常?这是一个问题 decltype(auto)=e相当于decltype(e)并产生声明的e类型 auto用作模板参数,这意味着auto&与T&(转发参考)对于一个虚构的模板参数是相同的 对于f1,返回类型推断为int 对于f2而言,返回类型auto&相当于T&,它是左值e的类型,这
decltype(auto)
只有三种可能的推断类型:
auto
auto&
auto&
f4
错误,而其他三个都正常?这是一个问题
decltype(auto)=e
相当于decltype(e)
并产生声明的e
类型
auto
用作模板参数,这意味着auto&
与T&
(转发参考)对于一个虚构的模板参数是相同的
对于f1,返回类型推断为int
对于f2而言,返回类型auto&
相当于T&
,它是左值e
的类型,这里您将int&
绑定到e
<强> f3强>考虑如下:
#include <type_traits>
#include <utility>
int main()
{
auto f1 = [](auto&& e) -> auto
{
return e;
};
auto f2 = [](auto&& e) -> auto&
{
return e;
};
auto f3 = [](auto&& e) -> auto&&
{
return e;
};
auto f4 = [](auto&& e) -> decltype(auto)
{
return e;
};
int n{};
f1(std::move(n)); // ok
f2(std::move(n)); // ok
f3(std::move(n)); // ok
f4(std::move(n)); // error
}
auto&& t = n;
static_assert(std::is_same_v<decltype(t), int&>); // true
f4
的参数也是用xvaluestd::move(n)
初始化的转发引用T&
,由此推断T=int
产生参数int&&e
。返回类型为decltype(auto)
和return e
意味着实际返回是decltype(e)
,然后正如您所看到的(1)是真的,对decltype(e)
的保留相同,这意味着f4
的实际返回是int&
。。。问题是,f4
试图将右值int&
绑定到左值e
,这是被禁止的
您还可以查看GCC错误。该错误来自于叮当声。GCC似乎接受了这一点。我猜这是一个叮当作响的bug。Return type of
decltype(auto)
意味着返回e
导致返回类型为decltype(e)
,这是f4
@M的int&
。M为什么f3
正常而f4
不正常?@xmlmx自动&
返回类型在f3(std::move(n))
调用的实例化中推断为int&
,而e
可以初始化int&
应该auto&&t=n代码>be自动&t=std::move(n)代码>?这取决于你想做什么。。。您应该将其视为使用函数模板,例如f3
、int&
或int&
的推断返回类型是什么?@xmlmxint&
您可以使用静态断言(std::is_same_v)检查它代码>@xmllmx很高兴我能帮上忙
int&& r = 9;
static_assert(std::is_same_v<decltype(r), int&&>); // true (1)
decltype(auto) t = r; // fail with the same error you got.