C++模板
C++是一个面向对象编程的语言,提供了类的继承和组合机制,虽然在层次结构上很简单,但使用起来非常糟糕。C++使用关键字template,告诉编译器声明的类或者对象是一个模板。模板不是像继承和组合那样重用目标代码,而是重用源代码。容器不再包含名为 Object 的泛型基类,而是包含未指定的参数。与C语言中的宏定义有点类似,编译器可以将参数替换所需要的类型,使用模板比使用宏更加清晰和简单。
参考:Thinking in C++, Chapter 16
模板重载
模板语法:template <typename/class T> void func(T &, T &);
其中typename和class都可以表示类或者原始类型(int、double、char等),后面是函数函数返回类型void,函数名func,参数类型为T&,编译器会将T&转为所需要的类型,如int&、double&。
#include <iostream>using namespace std;/****************************/
//template overloadingtemplate <typename T>
void Swap(T &a, T &b);template <typename T>
void Swap(T *a, T *b, int);/****************************/int main()
{int a = 5, b = 7;Swap(a, b); cout << "a:" << a << ", b:" << b <<endl;double c = 5.6, d = 7.8;Swap(c, d);cout << "c:" << c << ", d:" << d <<endl;string s("abc");string t("def");Swap(s, t);cout << s << endl;cout << t << endl;const int n = 3;int e[n] = {1,2,3};int f[n] = {4,5,6};cout << "before swap:" << endl;for(int i = 0; i < n; i++)cout << e[i] << " ";cout << endl;for(int i = 0; i < n; i++)cout << f[i] << " ";Swap(e, f, n);cout << endl;cout << "after swap:" << endl;for(int i = 0; i < n; i++)cout << e[i] << " ";cout << endl;for(int i = 0; i < n; i++)cout << f[i] << " ";return 0;
}//template overloading definition
template <class T>
void Swap(T &a, T &b){T temp;temp = a;a = b;b = temp;
}//template overloading definition
template <class T>
void Swap(T *a, T *b, int n){for(int i = 0; i < n; i++){T temp;temp = a[i];a[i] = b[i];b[i] = temp;}
}
输出如下:
显式实例化和显式具体化
显式实例化(explicit instantiation),显式具体化(explicit specialization)。
显式实例化对应的是隐式实例化,上面的列子Swap(a, b)就是利用Swap的模板生成一个int类型的实例,即隐式实例化。
显式实例化语法:template void Swap<double>(double &, double &);
显示具体化语法:
template <> void Swap(double &, double &); 或者template<> void Swap<double>(double &, double &);
并且声明了显式具体化还需要对其进行定义,有了显式具体化告诉编译器不要使用Swap的原始模板来生成一个参数类型为double型Swap实例。
C++ Primer Plus书中写到:
#include <iostream>
#include <string>using namespace std;template <typename T>
void Swap(T &a, T &b);template <typename T>
void Swap(T *a, T *b, int);template <> void Swap<int>(int &, int &); //explicit specialization,必须定义
template void Swap<double>(double &, double &); //explicit instantiationint main()
{double a = 3.4, b = 5.6;Swap(a, b);return 0;
}//orginal template
template <class T>
void Swap(T &a, T &b){T temp;temp = a;a = b;b = temp;
}//显示具体化 (explicit specialization)
template <> void Swap<int>(int &a, int &b){int temp;temp = a;a = b;b = temp;
}