C++11 decay

One definition

  • Header file <type_traits>
template< class T >
struct decay; (since C++11)
  • Auxiliary type
template< class T >
using decay_t = typename decay<T>::type; (since C++14)

Two roles

  • Degradation type modification.
  • Apply implicit conversions from lvalue-to-rvalue, array-to-pointer, and function-to-pointer to type T. The conversion will remove the cv qualifiers (const and volatile) of type T and define the result type as decay< T >::type. This conversion is very similar to the conversion that occurs when function parameters are passed by value. There are several situations:
    • If T is the type of "array of U" or "reference to array of U", then decay< T >::type is U*.
    • If T is a function type F or a reference to it, then decay< T >::type is std::add_pointer< F >::type.
    • 否则,decay< T >::type 为 std::remove_cv<std::remove_reference< T >::type>::type。

Three examples

#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
}
  • result
true
true
true
true
true
true

Four references

Guess you like

Origin blog.csdn.net/luoshabugui/article/details/109853418