类型特征(type traits)有什么用?
为模板类型参数添加限制条件
如果不加限制条件,什么类型的变量都能传给函数,如果传入的变量不支持函数内的运算,则会编译出错,并且显示出来的出错信息可能和出错的真实原因相去甚远。
加了限制条件之后,如果传入的变量不满足条件同样会出错,但是给出的错误信息是预料之内的,更便于程序调试。
根据参数类型的不同,进行不同的操作
下面这个例子中用到了转发引用T&& x
。
错误的初次尝试:
改正:将std::is_same_v<T, int>
改为std::is_same_v<std::remove_cvref_t<T>, int>
。
标准库提供的相关类型特征有:
std::remove_const
,去除类型的 conststd::remove_reference
,去除类型的 引用std::remove_cvref
,同时去除类型的 const、volatile 和 引用。“cvref”是const
、volatile
和 reference 的缩写。关于 volatile,见什么是 volatile 类型std::remove_volatile
,去除类型的 volatile
更优雅一点,可以使用using
创建一个类型别名: