我们的max函数如下:
template <typename T> inline T const& max (T const& a, T const& b) { // if a < b then use b else use a return a < b ? b : a; }
我们传递的两个参数类型必须一致,编译器才能得出结论:T必须是你传递的类型。注意:这里不允许进行自动类型转换,每个T都必须正确的匹配。
max(4,7); 可以,两个实参都是int
max(4,4,2)不行,第一个int,第二个是double
有3中方法可以处理上面错误:
1.对实参进行强制类型转换,使他们可以相互匹配
max(static_cast<double>(4),4.2)
2.显示指定(或者限定)T的类型
max<double>(4,4.2)
3指定两个参数可以有不同类型。