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 the decay<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/
10-11 22:07
查看更多