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編程技法的理解