std::decay
来自cppreference.com
| 在标头 <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 结合 (类模板) |
| 隐式转换 | 数组到指针、函数到指针、左值到右值转换 |