Ema*_*res 12 c++ template-function c++11
经过多年的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;
}
Run Code Online (Sandbox Code Playgroud)
R S*_*ahu 16
除了想知道为什么会发生这种错误,
调用时Add(1.f, 2),第一个参数类型是float,第二个参数类型是int.
编译器必须将第一个参数转换为int第二个参数或将第二个参数转换为a float.由于它们都需要转换,因此它们同样适合.一个人不能优先于另一个人.
我想知道如何通过仅修改模板函数来解决以下错误
您可以将功能模板更改为:
template <class T1, class T2>
auto Add(T1 first, T2 second)
{
return first + second;
}
Run Code Online (Sandbox Code Playgroud)
或者(感谢@PiotrSkotnicki):
template <class T>
T Add(T first, decltype(first) second)
{
return first + second;
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,类型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.
Run Code Online (Sandbox Code Playgroud)
做就是了:
template <class T1, class T2>
auto Add(T1 first, T2 second)
{
return first + second;
}
Run Code Online (Sandbox Code Playgroud)
与独特一样T,它被推断为int一次,如double...