1. G2.9的type trait
G2.9的type trait用一个泛化类模板来定义各种类型的属性, 默认都是假的
然后给每一种类型都添加了偏特化版本, 这样的缺点是每写一个类, 都要添加一个偏特化的模板类, 十分麻烦
2. C++改进的type traits
自从C++11之后, 添加了很多种type traits, 如下:
我们可以写一个例子测试一下:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <set>
using namespace std;
template <typename T>
void test_type_trait_output(const T& x){
cout << "\ntype traits for type: " << typeid(T).name() << endl;
cout << "is_void\t" << is_void<T>::value << endl;
cout << "is_integral\t" << is_integral<T>::value << endl;
cout << "is_floating_point\t" << is_floating_point<T>::value << endl;
cout << "is_object\t" << is_object<T>::value << endl;
}
int main(int argc, char *argv[]){
string s;
test_type_trait_output(s);
return 0;
}
输出是:
type traits for type: NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
is_void 0
is_integral 0
is_floating_point 0
is_object 1
有没有感觉到很神奇, 为什么这种type_trait可以通过变量(对象)知道你有什么属性呢?
下面一起来分析一下:
3. type traits的实现原理
3.1 is_void的原理
- 调用
__is_void_helper
- 调用
remove_cv
去除const 和 volatile, 避免干扰 - 通过偏特化, 决定调用哪个
__is_void_helper
, 其中一个继承false_type
, 另一个继承true_type
.