c++ 類模板程式設計
阿新 • • 發佈:2022-03-09
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; }