type traits 负责萃取元素类型的特性,如果元素具有某个性质则我们调用某个函数,如果不具有某个性质则调用另一个函数。它充分利用了C++模板编程和编译器的参数推导功能(编译器只有面对类类型参数才会进行参数推导)。STL大量运用了traits编程技巧,通过模板特化,函数重载让编译器选择正确的处理方式,在编译期就能完成函数分发,极大的提高了灵活性。
先看一个例子
#include <iostream>
template <typename T>
struct is_void
{
static const bool value = false;
};
template <>
struct is_void<void>
{
static const bool value = true;
};
int main()
{
std::cout<<is_void<int>::value;//输出0
std::cout<<is_void<void>::value;//输出1
return 0;
}
我们对void类型进行了特化,使value = true, 对于其他所有类型value = false
traits简洁的说就是 :加上一层间接性,换取一定的灵活性
引用自http://www.cnblogs.com/pugang/archive/2012/10/17/2727378.html
再看另一段代码
/*
* STL type traits 编程技法
*/
#include <iostream>
using namespace std;
struct true_type {};
struct false_type {};
struct A{};
struct B{};
template <class type>
struct type_traits {
typedef false_type has_xxx; //默认为false_type
};
//特化A
template <>
struct type_traits<A> {
typedef true_type has_xxx;
};
//特化B
template <>
struct type_traits<B> {
typedef false_type has_xxx;
};
template <class T>
void test(T t) {
typedef typename type_traits<T>::has_xxx has_x;
_test(has_x());
};
void _test(true_type) {
cout << "1" << endl;
}
void _test(false_type) {
cout << "0" << endl;
}
int main() {
struct A a;
struct B b;
test(a); //输出1
test(b); //输出0
test(1); //输出0
test(3.5); //输出0
return 0;
}
type traits用来萃取元素特性,如果元素具有某个性质则do_something,否则do_otherthing.这个例子里对类类型A,B进行了特化,只有A类型里has_xxx(某个性质)为true_type,向函数test传递参数T时,type_traits进行特性萃取,将T中的has_xxx 赋予别名has_x,而在类型A中对true_type赋予别名has_xxx,所以这里的has_x 就是true_type类型,转调用函数_test,函数_test有两个版本,根据参数进行匹配,参数为true_type类型,输出1.调用test(b),test(1),test(3.5)输出0是一样的道理
以上就是我对type traits编程技法的理解