在STL中为了提供通用的操作而又不损失效率,有一种特殊的技巧: 元编程技巧。
元编程是 通过定义一些结构体或类,并利用模板类特化和偏特化的能力,给模板类型赋予一些特性(如引发C++的函数重载机制).
1、元编程的的特化版本
(1)默认的元编程模板版本
现在定义一个元编程可以获得类型的如下属性: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,然后在针对每个基本数据类型设计偏特化,可以实现函数的元编程效果.
(2)其他类型的偏特化模板
代码如下:
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;
};
其他基本类型的__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;
};
(3)自定义类型的偏特化模板
比如对与自定义的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;
};
2、元编程的使用
依赖特化的模板函数,实现元编程,可以调用不同的函数。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>();//会调用void _fun(_true_type),来源于template <>struct __type_traits<char> {...}
fun<int>();//会调用void _fun(_true_type),来源于template <>struct __type_traits<int> {...}
fun<char *>();//会调用void _fun(_true_type),来源于template <>struct __type_traits<_Tp*> {...}
fun<double>();//会调用_fun(_false_type) ,来源于template <class _Tp>struct __type_traits{...}
}