经过多年的 C++ 编码,今天我被问到一个简单的问题,但我确实找不到答案,所以我在这里。
除了想知道为什么会发生这个错误之外,我想知道如何我可以通过仅修改 模板函数(无需改变 main()
函数)
template <class T>
T Add(T first, T second)
{
return first + second;
}
int main()
{
auto sample_1 = Add(1, 2); // Works
auto sample_2 = Add(1.f, 2.f); // Works
auto sample_3 = Add(1.f, 2); // Error: no instance matches the argument types: (double, int)
return 0;
}
最佳答案
Besides wondering why this error is happening,
当你调用 Add(1.f, 2)
时,第一个参数类型是 float
,第二个参数类型是 int
。
编译器必须将第一个参数转换为 int
或将第二个参数转换为 float
。由于它们都需要转换,因此它们同样是不错的候选者。一个不能优于另一个。
I want to know how I can solve below error by modifying just the template function
您可以将函数模板更改为:
template <class T1, class T2>
auto Add(T1 first, T2 second)
{
return first + second;
}
或致(感谢@PiotrSkotnicki):
template <class T>
T Add(T first, decltype(first) second)
{
return first + second;
}
在这种情况下,second
的类型不是从传递给函数的参数中推断出来的。 first
的类型是从第一个参数推导出来的,second
的类型被强制与 first
的类型相同。
Add(1.2f, 2); // The first argument is deduced to be float
// The second argument is forced to be float.
Add(2, 1.2f); // The first argument is deduced to be int
// The second argument is forced to be int.
关于c++ - 没有使用模板功能从 `int` 到 `float` 的自动转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32914496/