跳转到内容

什么是 type traits(类型特征)?

顾名思义,就是类型是否满足条件。

如对于类型特征is_arithmetic,从名字“是数字”可以看出是用来判断类型是否是数字。

类型特征一般都是 struct,一般都有一个数据成员value,如果类型符合条件,那么value的值就是 true,否则就是 false。

一个例子

编写一个模板函数,如果函数参数是数字,打印一行文字;如果不是,打印另一种文字。

这个例子可以改进。使用 if constexpr 语句。

/*
编写一个模板函数,如果函数参数是数字,打印一行文字;如果不是,打印另一种文字。
*/
#include <iostream>
#include <type_traits>
template <typename T>
void func(const T& param) {
if (std::is_arithmetic_v<T>) {
std::cout << param << " is arithmetic" << std::endl;
} else {
std::cout << param << " is not arithmetic" << std::endl;
}
}
int main() {
int m{20};
std::string n{"nice"};
func(m);
func(n);
}

其他标准库类型特征

  • std::is_pointer,判断一个类型是否是指针。
  • std::is_class,判断一个类型是否是类(class, struct,不包括enum class, union)。
  • std::is_same,判断一个类型是否与另一个类型相同。
  • std::is_base_of,判断一个类型是否与另一个类型相同,或者说,该类型是否(通过继承)派生于另一个类型。

所有的标准库类型特征可以看这里:Standard library header <type_traits> (C++11) - cppreference.com

参考