std::decay
来自 cppreference.cn
定义于头文件 <type_traits> |
||
template< class T > struct decay; |
(自 C++11 起) | |
执行与通过值传递函数实参时执行的类型转换等效的类型转换。形式上
- 如果
T
是 “U
的数组” 或其引用,则成员 typedeftype
为U*
。
- 否则,如果
T
是函数类型F
或其引用,则成员 typedeftype
为 std::add_pointer<F>::type。
- 否则,成员 typedef
type
为 std::remove_cv<std::remove_reference<T>::type>::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>; int main() { 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)> ); }
[编辑] 参见
(C++20) |
组合了 std::remove_cv 和 std::remove_reference (类模板) |
隐式转换 | 数组到指针、函数到指针、左值到右值转换 |