在 C++中, Type Traits(类型特性)是一组模板类和函数, 它们提供了一种在编译时查询, 修改和操作类型信息的机制. Type Traits 是 C++ 标准库 <type_traits>
头文件的核心内容, 它利用了模板元编程(Template Meta Programming)的技术, 允许程序在编译时进行类型检查, 类型转换和类型选择等操作, 从而提高代码的安全性, 性能和灵活性.
主要用途
- 编译时类型检查: 可以在编译时确定某个类型是否满足特定的条件, 例如是否为整数类型, 是否为指针类型等.
- 类型转换: 在编译时对类型进行转换, 例如移除引用, 添加常量限定符等.
- 类型选择: 根据不同的条件在编译时选择不同的类型.
基础类型判断
这类 Traits 用于判断一个类型是否属于某种特定的类别, 返回一个布尔值. 常用的判断有:
is_integral
: 判断是否为整型is_floating_point
: 判断是否为浮点类型is_pointer
: 判断是否为指针类型
示例: 判断是否为整数类型
#include <iostream>
#include <type_traits>template <typename T>
void checkIfIntegral(T value) {if (std::is_integral<T>::value) {std::cout << "The type of the value is an integral type." << std::endl;} else {std::cout << "The type of the value is not an integral type." << std::endl;}
}int main() {int num = 42;double d = 3.14;checkIfIntegral(num);checkIfIntegral(d);return 0;
}
在上述代码中, std::is_integral<T>::value
用于判断类型 T
是否为整数类型. 如果是, 返回 true
; 否则返回 false
.
复合类型判断
此类查询包含有:
is_fundamental
is_object
is_compound
is_reference
is_member_point
类型属性
is_const
is_volatile
is_trivial
is_pod
查询支持的操作
is_constructable
is_nothrow_constructable
is_move_assignalbe
is_swappable
查询类型关系
is_same
is_base_of
is_convertible
is_invocable
2. 类型修改类
这类 Traits 用于在编译时修改类型, 例如添加或移除引用, 指针, 常量限定符等.
CV 相关
remove_cv
remove_const
remove_volatile
add_cv
add_const
add_volatile
引用
remove_reference
add_lvalue_reference
add_rvalue_reference
指针
remove_pointer
add_pointer
符号
make_signed
make_unsigned
3. 类型选择类
这类 Traits 用于根据条件在编译时选择不同的类型.
示例: 根据条件选择类型
#include <iostream>
#include <type_traits>template <typename T>
using ConditionalType =typename std::conditional<(sizeof(T) > 4), long, int>::type;template <typename T>
void printConditionalType() {using ResultType = ConditionalType<T>;std::cout << "The conditional type for " << typeid(T).name() << " is "<< typeid(ResultType).name() << std::endl;
}int main() {printConditionalType<char>();printConditionalType<double>();return 0;
}
在上述代码中, std::conditional<Condition, T1, T2>::type
根据条件 Condition
的真假选择 T1
或 T2
作为结果类型.
未完待续…
参考链接
- Type traits