gpt4 book ai didi

c++ decltype(auto) 或 decltype(std::forward(value))?

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

例如,简单的恒等仿函数:

template <typename T>
class identity
{
public:
constexpr auto operator ()(T && i) -> decltype(std::forward<T>(i))
{
return std::forward<T>(i);
}
};

对于返回值,什么更好(C++14 和更新版本):

  • -> decltype(std::forward<T>(i))
  • -> decltype(auto)

或者它们是一样的吗?

最佳答案

Or are they the same?

假设你写得正确:

constexpr decltype(auto) operator ()(T && i)
{
return std::forward<T>(i);
}

它们是一样的。 [dcl.type.auto.deduct] :

A type T containing a placeholder type, and a corresponding initializer e, are determined as follows:

  • for a non-discarded return statement that occurs in a function declared with a return type that contains a placeholder type, T is the declared return type and e is the operand of the return statement. If the return statement has no operand, then e is void();

If the placeholder is the decltype(auto) type-specifier, T shall be the placeholder alone. The type deduced for T is determined as described in [dcl.type.simple], as though e had been the operand of the decltype

函数的返回类型是从return e;推导出来的好像是 decltype(e) .所以它与显式 decltype(std::forward<T>(i)) 相同.

What is better

在这种情况下,我会选择“少即是多”。 decltype(auto)以更简洁的方式为您提供所需内容。

关于c++ decltype(auto) 或 decltype(std::forward<T>(value))?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47907661/

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