C++11 decay

一 定义

  • 头文件 <type_traits>
template< class T >
struct decay; (since C++11)
  • 辅助类型
template< class T >
using decay_t = typename decay<T>::type; (since C++14)

二 作用

  • 退化类型的修饰。
  • 为类型T应用从左值到右值(lvalue-to-rvalue)、数组到指针(array-to-pointer)和函数到指针(function-to-pointer)的隐式转换。转换将移除类型T的cv限定符(const和volatile),并定义结果类型为 decay< T >::type。这种转换很类似于函数参数按值传递时发生的转换。有以下几种情况:
    • 若 T 为“ U 的数组”或“到 U 的数组的引用”类型,则 decay< T >::type 为 U* 。
    • 若 T 为函数类型 F 或到它的引用,则 decay< T >::type 为 std::add_pointer< F >::type 。
    • 否则,decay< T >::type 为 std::remove_cv<std::remove_reference< T >::type>::type。

三 例子

#include <iostream>
#include <type_traits>
 
template <typename T, typename U>
struct decay_equiv : 
    std::is_same<typename std::decay<T>::type, U>::type 
{
    
    };
 
int main()
{
    
    
    std::cout << std::boolalpha
              << decay_equiv<int, int>::value << '\n'    // 情况3
              << decay_equiv<int&, int>::value << '\n'  // 情况3
              << decay_equiv<int&&, int>::value << '\n'  // 情况3
              << decay_equiv<const int&, int>::value << '\n'  // 情况3
              << decay_equiv<int[2], int*>::value << '\n' // 情况1
              << decay_equiv<int(int), int(*)(int)>::value << '\n'; // 情况2
}
  • 结果
true
true
true
true
true
true

四 参考

猜你喜欢

转载自blog.csdn.net/luoshabugui/article/details/109853418