c – auto,decltype(自动)和尾随返回类型

是否有区别:

template <class T>
constexpr decltype(auto) f(T&& x) -> decltype(std::get<0>(std::forward<T>(x)))
{
    return std::get<0>(std::forward<T>(x));
}

和:

template <class T>
constexpr auto f(T&& x) -> decltype(std::get<0>(std::forward<T>(x)))
{
    return std::get<0>(std::forward<T>(x));
}

如果是这样,它是什么,我应该使用哪一个来完美转发?

解决方法:

尾随返回类型只能与auto一起使用

decltype(auto)vs auto的点是distinguish the case whether the return type should be a reference or value.但在你的情况下,返回类型已经明确定义为decltype(std :: get< 0>(std :: forward< T>(x))),所以它即使您使用自动,也会完美转发.

在auto f()中 – > T,“auto”关键字只是一个syntactic construct to fill in a type position.它没有其他用途.

事实上,在C 17中,你不能同时使用带尾随返回类型的decltype(auto).

C 14措辞(n3936§7.1.6.4[dcl.spec.auto] / 1):

The auto and decltype(auto) type-specifiers designate a placeholder type that will be replaced later, either by deduction from an initializer or by explicit specification with a trailing-return-type. The auto type-specifier is also used to signify that a lambda is a generic lambda.

C 17措辞(n4618§7.1.7.4[dcl.spec.auto] / 1):

The auto and decltype(auto) type-specifiers are used to designate a placeholder type that will be replaced later by deduction from an initializer. The auto type-specifier is also used to introduce a function type having a trailing-return-type or to signify that a lambda is a generic lambda (5.1.5). The auto type-specifier is also used to introduce a decomposition declaration (8.5).

这是DR 1852,见Does a placeholder in a trailing-return-type override an initial placeholder?.

实际上,虽然gcc接受decltype(auto)f() – > T(which is a bug),但是clang会拒绝它说

error: function with trailing return type must specify return type 'auto',
not 'decltype(auto)'
上一篇:c – 使用lambda的dectltype作为模板参数


下一篇:c – 在decltype中使用命名空间