gpt4 book ai didi

c++ - auto、decltype(auto) 和尾随返回类型

转载 作者:太空狗 更新时间:2023-10-29 20:21:36 36 4
gpt4 key购买 nike

有区别吗:

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)对比autodistinguish the case whether the return type should be a reference or value .但在您的情况下,返回类型已明确定义为 decltype(std::get<0>(std::forward<T>(x))) , 因此即使您使用 auto 也会被完美转发.

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


事实上,在 C++17 中你不能使用 decltype(auto)与 trailing-return-type 一起。

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++ - auto、decltype(auto) 和尾随返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42744245/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com