- 函数模板
template<typename T>
T max(T a, T b) {
return a > b ? a : b;
}
或者将typename改为class,即
template<class T >
T max(T a, T b) {
return a > b ? a : b;
}
调用方式如下:
int main() {
int i = max<int>(3, 4);
cout << i << endl;
}
- 类模板
template <class numtype>//同理这里也可以将class替换为typename
class Compare {
public:
Compare(numtype a, numtype b) {
this->a = a;
this->b = b;
}
numtype max() {
return a > b ? a : b;
}
numtype min();
private:
numtype a, b;
};
//类外定义(比较麻烦)
template<class numtype>
numtype Compare <numtype>::min() {
return a < b ? a : b;
}
调用方式:
int main() {
Compare <int> cc(31, 32);
cout << cc.max() << endl;
}