一个函数模板:
template<class T> T
max(T a, T b){return (a > b)? a: b;}
使用时:
max<int>(a, b); // Yeah, the "<int>" is optional most of the time.
但如果你允许,我们可以这样写模板:
T max<class T>(T a, T b){return (a > b)? a: b;}
//I know the return type T is not in its scope, don't focus on that.
因此,我们可以像普通函数一样维护相同形式的声明和使用。甚至不需要引入和键入关键字“模板”。我认为类模板会是一样的吗?那么还有什么其他的原因让模板变成了我们今天所知道的形式吗?
我更改了表格,以便您不必关注返回类型:
auto max<class T>(T a, T b) -> T {return (a > b)? a: b;}
//This is C++11 only and ugly i guess.
//The type deduce happens at compile time
//means that return type really didn't to be a problem.