Namespaces
Variants

std:: decay

From cppreference.net
Metaprogramming library
Type traits
Type categories
(C++11)
(C++11) ( DR* )
Type properties
(C++11)
(C++11)
(C++14)
(C++11) (deprecated in C++26)
(C++11) ( until C++20* )
(C++11) (deprecated in C++20)
(C++11)
Type trait constants
Metafunctions
(C++17)
Supported operations
Relationships and property queries
Type modifications
Type transformations
(C++11) (deprecated in C++23)
(C++11) (deprecated in C++23)
decay
(C++11)
(C++11) ( until C++20* ) (C++17)

Compile-time rational arithmetic
Compile-time integer sequences
定义于头文件 <type_traits>
template < class T >
struct decay ;
(C++11 起)

执行与通过 函数参数 传值时进行的类型转换等效的类型转换。形式化表述:

  • 如果 T 是“ U 的数组”或其引用,则成员 typedef type U*
  • 否则,若 T 为函数类型 F 或其引用,则成员 typedef type std:: add_pointer < F > :: type

如果程序为 std::decay 添加特化,则行为未定义。

目录

成员类型

名称 定义
type T 应用退化类型转换后的结果类型

辅助类型

template < class T >
using decay_t = typename decay < T > :: type ;
(自 C++14 起)

可能的实现

template<class T>
struct decay
{
private:
    typedef typename std::remove_reference<T>::type U;
public:
    typedef typename std::conditional< 
        std::is_array<U>::value,
        typename std::add_pointer<typename std::remove_extent<U>::type>::type,
        typename std::conditional< 
            std::is_function<U>::value,
            typename std::add_pointer<U>::type,
            typename std::remove_cv<U>::type
        >::type
    >::type type;
};

示例

#include <type_traits>
template<typename T, typename U>
constexpr bool is_decay_equ = std::is_same_v<std::decay_t<T>, U>;
static_assert
(
    is_decay_equ<int, int> &&
    ! is_decay_equ<int, float> &&
    is_decay_equ<int&, int> &&
    is_decay_equ<int&&, int> &&
    is_decay_equ<const int&, int> &&
    is_decay_equ<int[2], int*> &&
    ! is_decay_equ<int[4][2], int*> &&
    ! is_decay_equ<int[4][2], int**> &&
    is_decay_equ<int[4][2], int(*)[2]> &&
    is_decay_equ<int(int), int(*)(int)>
);
int main() {}

参见

结合 std::remove_cv std::remove_reference
(类模板)
implicit conversion 数组到指针、函数到指针、左值到右值的转换