书上说:模板的特殊化是当模板中的pattern有确定的类型时,模板有一个具体的实现。例如假设我们的类模板pair 包含一个取模计算(module operation)的函数,而我们希望这个函数只有当对象中存储的数据为整型(int)的时候才能工作,其他时候,我们需要这个函数总是返回0。这可以通过下面的代码来实现:
// Template specialization
#include <iostream>
using namespace std;
template <class T>
class mypair {
T value1, value2;
public:
mypair (T first, T second){
value1=first;
value2=second;
}
T module () {return 0;}
};
template <>
class mypair <int> {
int value1, value2;
public:
mypair (int first, int second){
value1=first;
value2=second;
}
int module ();
};
template <>
int mypair<int>::module() {
return value1%value2;
}//这个函数为什么要声明成员函数,为什么不能在类里面呀?
int main () {
mypair <int> myints (100,75);
mypair <float> myfloats (100.0,75.0);
cout << myints.module() << '\n';
cout << myfloats.module() << '\n';
return 0;
}
这段带码,只有在vc6环境下可能运行,VC2008里报C2910错. 如果把函数放在类里面VC2008就可以了.