std::decay
存在的原因是什么? ?
在什么情况下是std::decay
有用吗?
最佳答案
std::atomic
类型为非放射性的。
N2609是提出 std::decay
的论文.论文解释:
Simply put,
decay<T>::type
is the identity type-transformation except if T is an array type or a reference to a function type. In those cases thedecay<T>::type
yields a pointer or a pointer to a function, respectively.
激发灵感的例子是 C++03 std::make_pair
:
template <class T1, class T2>
inline pair<T1,T2> make_pair(T1 x, T2 y)
{
return pair<T1,T2>(x, y);
}
它按值接受其参数以使字符串文字工作:
std::pair<std::string, int> p = make_pair("foo", 0);
如果它通过引用接受它的参数,那么 T1
会推导为数组类型,然后构造一个pair<T1, T2>
将是病态的。
但显然这会导致效率低下。因此需要 decay
, 以应用按值传递时发生的一组转换,使您可以通过引用获取参数的效率,但仍可以获得代码处理字符串文字、数组类型、函数所需的类型转换类型等:
template <class T1, class T2>
inline pair< typename decay<T1>::type, typename decay<T2>::type >
make_pair(T1&& x, T2&& y)
{
return pair< typename decay<T1>::type,
typename decay<T2>::type >(std::forward<T1>(x),
std::forward<T2>(y));
}
注意:这不是实际的 C++11 make_pair
实现 - C++11 make_pair
也展开 std::reference_wrapper
关于c++ - 什么是 std::decay 以及何时应该使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42384302/