标签:
函数模版
#include <iostream> using namespace std; template<typename T> T add(T t1, T t2) { return t1 + t2; } //template int add<int>(int t1, int t2); int main() { cout << add<int>(1.2, 3) << endl; }
类模版
#include <iostream> using namespace std; template <typename T> /** * 定义一个类模版, 并且实例化 */ class Compare { private: T t1, t2; public: Compare(T a, T b):t1(a),t2(b){} T max() { return t1 > t2 ? t1 : t2; } T min() { return t1 > t2 ? t2 : t1; } }; int main() { Compare<int> c1(1, 2); cout << "int max:" << c1.max() << endl; Compare<double> c2(1.2, 3.6); cout << "double min:" << c2.min() << endl; Compare<char> c3(‘a‘, ‘b‘); cout << "char max:" << c3.max() << endl; return 0; }
标签:
原文地址:http://www.cnblogs.com/bai-jimmy/p/5932273.html