我创建了一个带有 2 个不同模板参数 t1、t2 和返回类型 t3 的简单函数。 到目前为止没有编译错误。但是当我尝试从 main 调用该函数时,我遇到了错误 C2783。 我需要知道以下代码是否合法?如果不是,它是如何固定的? 请帮忙!
template <typename t1, typename t2, typename t3>
t3 adder1 (t1 a , t2 b)
{
return int(a + b);
};
int main()
{
int sum = adder1(1,6.0); // error C2783 could not deduce template argument for t3
return 0;
}
最佳答案
编译器无法推导出t3
从函数参数。您需要显式传递此参数。更改参数的顺序以使其成为可能
template <typename t3, typename t1, typename t2>
t3 adder1 (t1 a , t2 b)
{
return t3(a + b); // use t3 instead of fixed "int" here!
};
然后你可以用adder1<int>(1, 6.0)
调用它.如果要推导就更难了 t3
到加法的实际结果。 C++0x(下一个 C++ 版本的代号)将允许通过以下方式说返回类型等于加法类型来做到这一点
template <typename t1, typename t2>
auto adder1 (t1 a , t2 b) -> decltype(a+b)
{
return a + b;
};
然后你可以在使用时显式转换
int sum = (int) adder1(1,6.0); // cast from double to int
在当前的 C++ 版本中对此进行模拟并不容易。你可以用我的promote template要做到这一点。如果您觉得这会让您感到困惑,并且您可以明确提供返回类型,我认为最好继续明确提供它。喜欢Herb Sutter says “写你所知道的,知道你写的”
尽管如此,您可以使用该模板执行上述操作
template <typename t1, typename t2>
typename promote<t1, t2>::type adder1 (t1 a, t2 b)
{
return (a + b);
};
关于c++ - 奇怪的模板错误 : error C2783: could not deduce template argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2920600/