C++模板(5) - 模板特化

来源:互联网 发布:黄金投资 知乎 编辑:程序博客网 时间:2024/06/10 08:20
模板是C++中一个重要的特性。 只需要编写一次代码,就可以应用于多种数据类型,包含用户自定义类型。
例如,排序程序sort()可以用来对多种数据类型进行排序。一个stack类可以在多种数据类型中做为栈使用。

如果我们想用不同的代码来处理某个特定的数据类型,该如何实现?假设一个很大的工程中,很多个不同数据类型的数组,都需要使用到sort()函数。假设除了char类型之外,其它的都使用QuickSort(快速排序)。当类型是char时,因为总的可能数目是256,所以使用计数排序可能是一个更好的选择。有没有可能当数据类型是char时,调用的是某个特定的代码? 
C++中是可以支持针对某个特定数据类型而执行特定行为的。这个称为模板的特化。
// 一个通用的排序程序template <class T>void sort(T arr[], int size){    // 实现快速排序的代码}// 模板特化:指定char数据类型的函数template <>void sort<char>(char arr[], int size){    // 实现计数排序的代码}
另举一个例子,假设有一个类Set, 代表元素的集合,并且支持像union, intersection等操作。当元素类型为char时,我们可以使用一个简单的,大小为256个元素的布尔数组来实现这个集合。当元素类型为其它时,则可能需要使用一些其它的复杂操作来实现。


函数模板特化的例子

参考下面程序,定义了一个模板函数fun(),对其它所有数据类型都适用,除了int类型。对于int, 有一个特定版本的fun()。

#include <iostream>using namespace std;template <class T>void fun(T a){   cout << "The main template fun(): " << a << endl;}template<>void fun(int a){    cout << "Specialized Template for int type: " << a << endl;}int main(){    fun<char>('a');    fun<int>(10);    fun<float>(10.14);}
输出:
The main template fun(): a
Specialized Template for int type: 10
The main template fun(): 10.14

模板类特化的例子
下面程序中,模板类中,对于int数据类型有一个特定版本。

#include <iostream>using namespace std;template <class T>class Test{  // Data memnbers of testpublic:   Test()   {       // Initializstion of data memnbers       cout << "General template object \n";   }   // Other methods of Test};template <>class Test <int>{public:   Test()   {       // Initializstion of data memnbers       cout << "Specialized template object\n";   }};int main(){    Test<int> a;    Test<char> b;    Test<float> c;    return 0;}

输出:
Specialized template object
General template object
General template object

模板特化如何工作?
当编写了一个模板函数或模板类后,如果编译器碰到了一个新的数据类型,或新的数据类型集合(多个模板参数的情况下),则编译器会创建一份模板函数/模板类的拷贝。
如果提供了一个特定的版本,编译器会优先检查这个特定版本,然后再使用主模板。在一个特定版本中,编译器会优先检查特化最多的版本,依据的是传入参数匹配最多。

0 0
原创粉丝点击