类型特性
类型特性定义一个编译时基于模板的结构,以查询或修改类型的属性。
试图特化定义于 <type_traits> 头文件的模板导致未定义行为,除了 std::common_type 可依照其所描述特化。
定义于<type_traits>头文件的模板可以用不完整类型实例化,除非另外有指定,尽管通常禁止以不完整类型实例化标准库模板。
杂项变换
实施当按值传递实参给函数时所进行的类型变换
std::decay
template< class T > | (C++11 起) |
对类型 T
应用左值到右值、数组到指针及函数到指针隐式转换,移除 cv 限定符,并定义结果类型为成员 typedef type
。正式而言:
- 若
T
指名“U
的数组”或“到U
的数组的引用”类型,则成员 typedeftype
为 U* 。
- 否则,若
T
为函数类型F
或到它的引用,则成员 typedeftype
为std::add_pointer<F>::type 。
- 否则,成员 typedef
type
为 std::remove_cv<std::remove_reference<T>::type>::type 。
这些转换模仿在以值传递时,应用到所有函数参数的类型转换。
成员类型
名称 | 定义 |
type | 应用退化类型转换到 T 的结果 |
辅助类型
template< class T > | (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::remove_extent<U>::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 <iostream>
#include <type_traits>int main()
{std::cout << std::boolalpha;std::cout << "std::is_same<std::decay<int>::type, int>::type: "<< std::is_same<std::decay<int>::type, int>::type() << std::endl;std::cout << "std::is_same<std::decay<int&>::type, int>::type: "<< std::is_same<std::decay<int&>::type, int>::type() << std::endl;std::cout << "std::is_same<std::decay<int&&>::type, int>::type: "<< std::is_same < std::decay < int&& >::type, int >::type() << std::endl;std::cout << "std::is_same<std::decay<const int&>::type, int>::type:"<< std::is_same<std::decay<const int&>::type, int>::type() << std::endl;std::cout << "std::is_same<std::decay<int[2]>::type, int*>::type: "<< std::is_same<std::decay<int[2]>::type, int*>::type() << std::endl;std::cout << "std::is_same<std::decay<int>::type, int>::type: "<< std::is_same<std::decay<int(int)>::type, int(*)(int)>::type() << std::endl;std::cout << std::endl;
}
输出
std::is_same<std::decay<int>::type, int>::type: true
std::is_same<std::decay<int&>::type, int>::type: true
std::is_same<std::decay<int&&>::type, int>::type: true
std::is_same<std::decay<const int&>::type, int>::type:true
std::is_same<std::decay<int[2]>::type, int*>::type: true
std::is_same<std::decay<int>::type, int>::type: true