c++ decltype(auto) 或 decltype(std::forward<T>(value))?
c++ decltype(auto) or decltype(std::forward<T>(value))?
例如,简单的恒等函子:
template <typename T>
class identity
{
public:
constexpr auto operator ()(T && i) -> decltype(std::forward<T>(i))
{
return std::forward<T>(i);
}
};
return 值更好(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 类型是从 return e;
推导出来的,就像 decltype(e)
一样。所以它与显式 decltype(std::forward<T>(i))
.
相同
What is better
在这种情况下,我会选择 "less is more"。 decltype(auto)
以更简洁的方式为您提供所需内容。
例如,简单的恒等函子:
template <typename T>
class identity
{
public:
constexpr auto operator ()(T && i) -> decltype(std::forward<T>(i))
{
return std::forward<T>(i);
}
};
return 值更好(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 initializere
, 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 ande
is the operand of the return statement. If the return statement has no operand, thene
isvoid()
;If the placeholder is the
decltype(auto)
type-specifier,T
shall be the placeholder alone. The type deduced forT
is determined as described in [dcl.type.simple], as thoughe
had been the operand of thedecltype
函数的 return 类型是从 return e;
推导出来的,就像 decltype(e)
一样。所以它与显式 decltype(std::forward<T>(i))
.
What is better
在这种情况下,我会选择 "less is more"。 decltype(auto)
以更简洁的方式为您提供所需内容。