尾随返回类型只能与auto
要点是decltype(auto)
vs auto
is to 区分返回类型是引用还是值 https://stackoverflow.com/questions/21369113/what-is-the-difference-between-auto-and-decltypeauto-when-returning-from-a-fun。但在你的情况下,返回类型已经明确定义为decltype(std::get<0>(std::forward<T>(x)))
,所以即使你使用它也会被完美转发auto
.
In auto f() -> T
,“auto”关键字只是一个用于填充类型位置的语法结构 https://stackoverflow.com/questions/12224325/what-is-the-meaning-of-auto-when-using-c-trailing-return-type。它没有其他目的。
事实上,在 C++17 中你cannot use a decltype(auto)
与尾随返回类型一起。
C++14 措辞 (n3936 §7.1.6.4[dcl.spec.auto]/1):
The auto
and decltype(auto)
类型说明符指定一个占位符类型,稍后将通过从初始值设定项推导或使用显式指定来替换尾随返回类型. The auto
类型说明符也用于表示 lambda 是通用 lambda。
C++17 措辞 (n4618 §7.1.7.4[dcl.spec.auto]/1):
The auto
and decltype(auto)
类型说明符用于指定占位符类型,稍后将通过从初始值设定项推导来替换该占位符类型。这auto
类型说明符也用于引入具有尾随返回类型或者表示 lambda 是通用 lambda (5.1.5)。这auto
类型说明符也用于引入分解声明(8.5)。
This is DR 1852 http://open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1852, see 尾随返回类型中的占位符是否会覆盖初始占位符? https://stackoverflow.com/questions/24259947/does-a-placeholder-in-a-trailing-return-type-override-an-initial-placeholder.
实际上,虽然gcc
接受decltype(auto) f() -> T
(这是一个错误 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67012), but clang
will reject它说
error: function with trailing return type must specify return type 'auto',
not 'decltype(auto)'