类型特性
类型特性定义一个编译时基于模板的结构,以查询或修改类型的属性。
试图特化定义于 <type_traits> 头文件的模板导致未定义行为,除了 std::common_type 可依照其所描述特化。
定义于<type_traits>头文件的模板可以用不完整类型实例化,除非另外有指定,尽管通常禁止以不完整类型实例化标准库模板。
类型修改
类型修改模板通过应用修改到模板参数,创建新类型定义。结果类型可以通过成员 typedef type 访问。
添加 const 或/与 volatile 限定符到给定类型
std::add_cv,
std::add_const,
std::add_volatile
template< class T > | (1) | (C++11 起) |
template< class T > | (2) | (C++11 起) |
template< class T > | (3) | (C++11 起) |
提供同 T
的成员 typedef type
,除了它拥有添加的 cv 限定符(除非 T
是函数、引用或已拥有 cv 限定符)。
1) 添加 const 和 volatile
2) 添加 const
3) 添加 volatile
成员类型
名称 | 定义 |
type | 带 cv 限定符的类型 T |
辅助类型
template< class T > | (C++14 起) | |
template< class T > | (C++14 起) | |
template< class T > | (C++14 起) |
可能的实现
template< class T >
struct add_cv { typedef const volatile T type; };template< class T> struct add_const { typedef const T type; };template< class T> struct add_volatile { typedef volatile T type; };
调用示例
#include <iostream>
#include <type_traits>struct foo
{void m(){std::cout << "Non-cv" << std::endl;}void m() const{std::cout << "Const" << std::endl;}void m() volatile{std::cout << "Volatile" << std::endl;}void m() const volatile{std::cout << "Const-volatile" << std::endl;}
};int main()
{foo{}.m();std::cout << "std::add_const<foo>::type: ";std::add_const<foo>::type{}.m();std::cout << "std::add_volatile<foo>::type: ";std::add_volatile<foo>::type{}.m();std::cout << "std::add_cv<foo>::type: ";std::add_cv<foo>::type{}.m();return 0;
}
输出
Non-cv
std::add_const<foo>::type: Const
std::add_volatile<foo>::type: Volatile
std::add_cv<foo>::type: Const-volatile