在STL中為了提供通用的操作而又不損失效率,我們用到了一種特殊的技巧,叫traits編程技巧。具體的來說,traits就是
通過定義一些結構體或類,并利用模板類特化和偏特化的能力,給類型賦予一些特性,這些特性根據類型的不同而異。在程序設計中可以使用這些traits來判
斷一個類型的一些特性,引發C++的函數重載機制,實現同一種操作因類型不同而異的效果。traits的編程技巧極度彌補了C++語言的不足 。
舉例:
現在定義一個__type_traits可以獲得類型的如下屬性:
1. 是否存在non-trivial default constructor
2. 是否存在non-trivial copy constructor
3. 是否存在non-trivial assignment operator
4. 是否存在non-trivial destructor
struct __true_type {
};
struct __false_type {
};
template <class _Tp>
struct __type_traits {
typedef __false_type has_trivial_default_constructor;
typedef __false_type has_trivial_copy_constructor;
typedef __false_type has_trivial_assignment_operator;
typedef __false_type has_trivial_destructor;
};
問題:為什么把對象的所有的屬性都定義為__false_type?
這樣是采用最保守的做法,先把所有的對象屬性都設置為__false_type,然后在針對每個基本數據類型設計特化的__type_traits,就可以達到預期的目的,如可以定義__type_traits<int>如下:
template <>
struct __type_traits<int> {
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_operator;
typedef __true_type has_trivial_destructor;
};
template <>
struct __type_traits<char> {
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_operator;
typedef __true_type has_trivial_destructor;
};
......
......
其他基本類型的traits也可以有相應的定義
__type_traits的偏特化版本
template <class _Tp>
struct __type_traits<_Tp*> {
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_operator;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
我們可以自定義__type_traits的特化版本
比如對與自定義的Shape類型,我們可以這樣定義__type_traits<Shape>
struct __type_traits<Shape> {
typedef __false_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_operator;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
如果編譯器夠厲害,我們甚至可以不用自己去定義特化的__type_traits,編譯器就能夠幫我們搞定:)
如何使用呢?
假設現在用個模板函數fun需要根據類型T是否有non-trivial constructor來進行不同的操作,可以這樣來實現:
template<class T>
void fun()
{
typedef typename __type_traits<T>::has_trivial_constructor _Trivial_constructor;
__fun(_Trivial_constructor()); // 根據得到的_Trivial_constructor來調用相應的函數
}
// 兩個重載的函數
void _fun(_true_type)
{
cout<<"fun(_true_type)called"<<endl;
}
void _fun(_false_type)
{
cout<<"fun(_false_type) called"<<endl;
}
//測試代碼
int main()
{
fun<char>();
fun<int>();
fun<char *>();
fun<double>();
}
posted on 2010-10-11 09:24
小果子 閱讀(1613)
評論(0) 編輯 收藏 引用 所屬分類:
C++