我很少看到,decltype(auto)但是当我这样做时,它会让我感到困惑,因为它似乎与auto从函数返回时一样.
auto g() { return expr; }
decltype(auto) g() { return expr; }
Run Code Online (Sandbox Code Playgroud)
这两种语法有什么区别?
而不是平常
void foo (void ) {
cout << "Meaning of life: " << 42 << endl;
}
Run Code Online (Sandbox Code Playgroud)
C++11 允许是另一种选择,使用追踪回报
auto bar (void) -> void {
cout << "More meaning: " << 43 << endl;
}
Run Code Online (Sandbox Code Playgroud)
在后者 - 什么是auto代表?
另一个例子,考虑功能
auto func (int i) -> int (*)[10] {
}
Run Code Online (Sandbox Code Playgroud)
同样的问题,auto这个例子中的含义是什么?
克++出现接受的任何组合auto和decltype(auto)作为初始和结尾返回类型:
int a;
auto f() { return (a); } // int
auto g() -> auto { return (a); } // int
auto h() -> decltype(auto) { return (a); } // int&
decltype(auto) i() { return (a); } // int&
decltype(auto) j() -> auto { return (a); } // int
decltype(auto) k() -> decltype(auto) { return (a); } // int&
Run Code Online (Sandbox Code Playgroud)
但是,clang拒绝j并且k说:error:具有尾随返回类型的函数必须指定返回类型'auto',而不是'decltype(auto)'(演示).
哪个编译器正确?在每种情况下应该使用哪个规则(auto或decltype(auto))?在尾随返回类型中使用占位符类型是否有意义?
c++ decltype trailing-return-type return-type-deduction c++14