我正在学习函数模板,但我在下面创建的模板无法编译,我不确定哪里出了问题。我试图让一个 int 变量和一个 double 变量进入模板,但是当我调用函数时我总是收到错误。错误是:
error: no matching function for call to 'LargestFunction(int&, double&)'|
代码如下:
template <class Temp>
Temp LargestFunction(Temp a, Temp b){
if(a > b){
return a;
}
else
return b;
}
int main()
{
int NumOne = 30;
double NumTwo = 52.252;
cout << LargestFunction(NumOne,NumTwo);
return 0;
}
最佳答案
如果要支持不同的类型,需要定义不同模板参数的模板。
template <typename Lhs, typename Rhs> typename std::common_type<Lhs, Rhs>::type max(const Lhs &lhs, const Rhs &rhs) { return lhs > rhs ? lhs : rhs; }
这样你就可以传递不同的类型,你会得到它们之间的共同类型。
如果您只想处理函数内的相同类型,您可以保持模板不变。
template <typename T> T max(const T &lhs, const T &rhs) { return lhs > rhs ? lhs : rhs; }
然后您需要强制转换其中一个参数,以便拥有相同的类型。
max(static_cast<double>(101), 4.2);
或者,您也可以显式特化函数模板,但通常不鼓励这样做。
max<double>(101, 4.2);
关于c++ - 函数模板无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20602831/