【发布时间】:2018-06-07 09:01:58
【问题描述】:
#include <iostream>
// maximum of two values of any type:
template<typename T>
T max (T a, T b)
{
std::cout << "max<T>() \n";
return b < a ? a : b;
}
// maximum of three values of any type:
template<typename T>
T max (T a, T b, T c)
{
return max (max(a,b), c); // uses the template version even for ints
} //because the following declaration comes
// too late:
// maximum of two int values:
int max (int a, int b)
{
std::cout << "max(int,int) \n";
return b < a ? a : b;
}
int main()
{
::max(47,11,33); // OOPS: uses max<T>() instead of max(int,int)
}
在这个例子中(来自下面提到的书)我不明白为什么 ::max(47,11,33) 调用预期使用 max(int,int)。所以一个是 2 个参数,另一个是 3 个参数,我认为它应该使用 3 个参数函数定义。
我错过了什么吗?
注意:David Vandevoorde、Nicolai M. Josuttis、Douglas Gregor C++ 模板:完整指南 [第 2 版] 一书
【问题讨论】:
-
按照定义函数的顺序进行操作。例如,如果您在三参数模板函数之前定义(或至少声明)
int max(int, int)函数会发生什么?或者如果你使用 specialization 而不是重载呢?喜欢template<> int max(int, int);。 -
使用模板而不是非模板重载的是对 max(a,b) inside max(a,b,c) 的调用。
-
@Mat 谢谢我现在注意到了。
-
@user463035818 是的,但是“你错过了阅读 cmets”的答案并不能很好地回答这个问题