类型萃取,字面理解(type traits)
#include<iostream>
using namespace std;
template<class T>
class A
{
public:
A()
:a(0)
{
cout << "初始的模板" << endl;
}
T a;
};
template<>
class A<int>
{
public:
A()
:a(0)
{
cout << "全特化" << endl;
}
int a;
};
void test_template()
{
A<char> first;
A<int> second;
}
在这种假设中,我们可以认为特化后的int处理会比其他类型使用初始模板好,于是使用了特化。
这个是全特化,自然,还有偏特化。
template< class T>
class Test<int,T>
{
public:
Test()
{
cout << "Test 偏特化" << endl;
}
};
//偏特化
下面是STL中针对不同类型特化,很好理解,一个自定义对象的操作和一个人普通内置类型int的操作就应该不一样,而模板接口接受参数时,统一是自定义T接受,然后处理上分开处理,便是C++的性能优势。
// 代表内置类型
struct __true_type {};
// 代表自定义类型
struct __false_type {};
template <class type>
struct __type_traits
{
typedef __false_type is_POD_type;
};
// 对所有内置类型进行特化
template<>
struct __type_traits<char>
{
typedef __true_type is_POD_type;
};
template<>
struct __type_traits<signed char>
{
typedef __true_type is_POD_type;
};
template<>
struct __type_traits<unsigned char>
{
typedef __true_type is_POD_type;
};