什么是std :: decay和什么时候应该使用? [英] What is std::decay and when it should be used?
问题描述
std :: decay $ c $的存在的原因是什么c>
?
在什么情况下是 std :: decay
有用?
< joke>明显用于衰变放射性 std < / j>
www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2069.html\"> N2609 是提出 std :: decay $ c $的论文c>。本文解释:
简单地说,decay :: type是标识类型转换,除了
,如果T是数组类型或对函数类型的引用。在那些
的情况下,decay :: type分别产生一个指针或指向一个函数的指针
。
激励的例子是C ++ 03 std :: make_pair
:
template< class T1,class T2>
内联对< T1,T2> make_pair(T1x,T2y)
{
return pair< T1,T2>(x,y);
}
它通过值接受其参数以使字符串文字工作:
std :: pair< std :: string,int> p = make_pair(foo,0);
如果它通过引用接受其参数,则 T1
将被推导为数组类型,然后构造对< T1,T2>
将会是错误的。
$ b $但是,这显然导致显着的低效率。因此,需要
decay
,以应用在传递值发生时发生的一组变换,从而允许您通过引用获取参数的效率,但仍然获取您的代码使用字符串字面量,数组类型,函数类型等所需的类型转换: template<类T1,类T2>
inline pair< typename decay< T1> :: type,typename decay< T2> :: type>
make_pair(T1&& x,T2& y)
{
return pair< typedes decay< T1> :: type,
typename decay< T2> :: type>(std :: forward< T1>(x),
std :: forward& ;
}
注意:这不是实际的C + +11 make_pair
实现 - C ++ 11 make_pair
也解包 std :: reference_wrapper
s。
What are the reasons for the existence of std::decay
?
In what situations is std::decay
useful?
<joke>It's obviously used to decay radioactive std::atomic
types into non-radioactive ones.</joke>
N2609 is the paper that proposed std::decay
. The paper explains:
Simply put, decay::type is the identity type-transformation except if T is an array type or a reference to a function type. In those cases the decay::type yields a pointer or a pointer to a function, respectively.
The motivating example is 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);
}
which accepted its parameters by value to make string literals work:
std::pair<std::string, int> p = make_pair("foo", 0);
If it accepted its parameters by reference, then T1
will be deduced as an array type, and then constructing a pair<T1, T2>
will be ill-formed.
But obviously this leads to significant inefficiencies. Hence the need for decay
, to apply the set of transformations that occurs when pass-by-value occurs, allowing you to get the efficiency of taking the parameters by reference, but still get the type transformations needed for your code to work with string literals, array types, function types and the like:
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));
}
Note: this is not the actual C++11 make_pair
implementation - the C++11 make_pair
also unwraps std::reference_wrapper
s.
这篇关于什么是std :: decay和什么时候应该使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!