我创建了一个带有2个diffrernt模板参数t1,t2和返回类型t3的简单函数.到目前为止没有编译错误.但是当Itry从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;
}
Run Code Online (Sandbox Code Playgroud)
Joh*_*itb 10
编译器无法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!
};
Run Code Online (Sandbox Code Playgroud)
然后你可以用它来调用它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;
};
Run Code Online (Sandbox Code Playgroud)
然后你可以在使用点明确地施放
int sum = (int) adder1(1,6.0); // cast from double to int
Run Code Online (Sandbox Code Playgroud)
在当前的C++版本中模拟这并不容易.您可以使用我的促销模板来执行此操作.如果您觉得这对您来说相当困惑,并且您可以明确地提供返回类型,我认为最好继续明确地提供它.像Herb Sutter所说: "写下你所知道的,知道你写的是什么"
尽管如此,您可以使用该模板执行上述操作
template <typename t1, typename t2>
typename promote<t1, t2>::type adder1 (t1 a, t2 b)
{
return (a + b);
};
Run Code Online (Sandbox Code Playgroud)