C++ 对于自动类型推断参数,decltype(auto)应该推断什么?
我认为这两个函数应该具有相同的返回类型:C++ 对于自动类型推断参数,decltype(auto)应该推断什么?,c++,c++-concepts,type-deduction,type-declaration,C++,C++ Concepts,Type Deduction,Type Declaration,我认为这两个函数应该具有相同的返回类型: template<class T> decltype(auto) f(T&& a){return a;} decltype(auto) g(auto&& a){return a;} 模板 decltype(auto)f(T&&a){返回a;} decltype(auto)g(auto&&a){返回a;} 然而,使用gcc7,这些功能验证: int i; static_assert(std::is_same&
template<class T>
decltype(auto) f(T&& a){return a;}
decltype(auto) g(auto&& a){return a;}
模板
decltype(auto)f(T&&a){返回a;}
decltype(auto)g(auto&&a){返回a;}
然而,使用gcc7,这些功能验证:
int i;
static_assert(std::is_same< decltype(f(i)), int& >::value);
static_assert(std::is_same< decltype(g(i)), int >::value);
inti;
静态断言(std::is_same:value);
静态断言(std::is_same::值);
为什么g和f的返回类型不同?定义
decltype(auto) g(auto&& a){return a;}
不是标准C++。这可能是即将推出的概念Lite功能的一部分。g++提供语法作为扩展(即使没有
-fconcepts
)
使用-Wpedantic
编译实际上会产生一个警告:
warning: ISO C++ forbids use of 'auto' in parameter declaration [-Wpedantic]
decltype(auto) g(auto&& a){return a;}
^~~~
由于行为尚未标准化,因此尚不清楚您的static\u assert
是否应该真实-直觉上我同意decltype(g(I))
应该是int&
。这可能只是g++实现非成员函数auto
参数的“缺陷”
最符合标准的是lambda表达式: 在
z
的情况下,static_assert
按预期工作:
static_assert(std::is_same< decltype(z(i)), int& >::value);
静态断言(std::is_same<代码> > DECKECTOL(AUTO)G(Auto&A){返回;a } /Comp>不是标准C++。看起来它们应该是等价的。在我指定的C++列表中,自动参数推导不包括在即将到来的标准中。@ OLIVO,它们是概念TS的一部分,它们不包含在内。
static_assert(std::is_same< decltype(z(i)), int& >::value);