1.头文件
//单参数类模板 #ifndef _OPERATOR_H #define _OPERATOR_H #include<iostream> using namespace std; //单个参数函数模板 template < typename T > class Operator { public: T add(T a, T b); T minus(T a, T b); T multiply(T a, T b); T divide(T a, T b); }; //多个参数函数模板 template < typename T1,typename T2 > class Operator_1 { public: void add(T1 a, T2 b); }; //类模板特化-完全特化 template <> class Operator_1< int , int> { public: void add(int a, int b) { cout<<a+b<<endl; } }; //部分特化,当两个参数都是指针调用该参数 template < typename T1,typename T2 > class Operator_1<T1*,T2*> //部分特化的类模板,当两个参数都是指针,调用这个 { public: void add(T1* a, T2* b) { cout<<"add(T1* a, T2* b)"<<endl; cout<<*a+*b<<endl; } }; template < > class Operator_1<void*,void*> //完全特化的类模板,当两个参数都是void*,调用这个 { public: void add(void* a, void* b) { cout<<"add(void* a, void* b)"<<endl; cout<<"add void* Error"<<endl; //void*无法进行加法 } }; template < typename T > //外部定义的成员函数,都需要加上模板声明 T Operator<T> :: add(T a, T b) //同时加上结构体<T>声明 { return a+b; } template < typename T > T Operator<T> :: minus(T a, T b) { return a-b; } template < typename T > T Operator<T> :: multiply(T a, T b) { return a*b; } template < typename T > T Operator<T> :: divide(T a, T b) { return a/b; } template < typename T1,typename T2 > void Operator_1<T1,T2 > :: add(T1 a, T2 b) { cout<<a+b<<endl; } #endif
2.cpp文件
#include<string> #include"Operator.h" using namespace std; string operator-(string &l,string r) { return "minus"; } int main() { Operator<int> op1; op1.add(1,2); cout<<op1.add(1,2)<<endl; Operator_1 <int ,float>op2; op2.add(1,2); Operator_1<int,int>op3; op3.add(1000,2000); int *p1 = new int(1); float *p2 = new float(1.25); Operator_1<int*,float*> Op4; //匹配部分特化的类模板:class Operator<T1*,T2*> Op4.add(p1,p2); Operator_1<void*,void*> Op5; //匹配完全特化的类模板:class Operator<void*,void*> Op5.add(NULL,NULL); delete p1; delete p2; return 0; }