C++模板的应用
1、先看类模板的应用,直接上例子:
#include <iostream> using namespace std; template <typename T> typename Compare { public: Compare(T a, T b) { this->x = a; this->y = b; } T max() { return x>y?x:y; } T min() { return x<y?x:y; } T sayHello(); //{ // cout<<sizeof(T)<<endl; //} private: T x,y; }; template <typename T> T Compare<T>::sayHello() { cout<<sizeof(T)<<endl; } int main() { Compare<int> cmp1(3,7); cout<<cmp1.max()<<endl; cout<<cmp1.min()<<endl; Compare<float> cmp2(1.1,2.2); cout<<cmp2.max()<<endl; cout<<cmp2.min()<<endl; cmp1.sayHello(); }
其实跟C#中的也没什么区别,只不过当在外部定义的时候有小小要注意的地方。
2、普通类中定义模板函数
#include <iostream> using namespace std; class Compare { public: template <typename T> void sayHello(); //{ // cout<<sizeof(T)<<endl; //} }; template <typename T> void Compare::sayHello() { cout<<sizeof(T)<<endl; } int main() { Compare cmp1; cmp1.sayHello<int>(); }
也是清晰易懂简单明了