如何实现通用的max函数? [英] How to implement generic max function?
问题描述
我知道这是因为模板函数的返回类型与第一个参数(T)的返回类型相同.
如何修改此模板,使其在所有情况下都能正常运行?
I know this is because the return type of the template function is same as that of the first argument (T).
How can I modify this template so that, it behaves correctly in all cases?
#include <iostream>
using namespace std;
template <typename T, typename U>
T max(T x, U y)
{
return x>y ? x : y;
}
int main()
{
cout<<max(17.9,17)<<"\n";
cout<<max(17,17.9)<<"\n";
}
输出:
17.9
17
推荐答案
输出正确.您从未指定类型,因此抱怨它没有使用您希望它使用的类型是不合理的.如果你想要一个特定的类型,你必须确保两个参数都是那个类型.
The output is correct. You never specified a type, so complaining that it didn't use the type you wanted it to use is not reasonable. If you want a specific type, you have to ensure both parameters are that type.
您可以将第一个参数转换为 double
.或者你可以专门调用
max
.如果您真的非常想要,您也可以专门化 max
和类似的组合.
You could cast the first parameter to a double
. Or you could specifically invoke
max<double, double>
. You could also specialize max<int, double>
and similar combinations if you really, really wanted to.
这篇关于如何实现通用的max函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!