[英]Why does compiler throw an error when we declare an extra template argument and not used in definition?
I have a below code. 我有下面的代码。
#include <iostream>
template <class T,class U>
T myMax(T x, T y)
{
return (x > y)? x: y;
}
int main()
{
std::cout << myMax(3, 7) << std::endl; // Call myMax for int
std::cout << myMax(3.0, 7.0) << std::endl; // call myMax for double
std::cout << myMax('g', 'e') << std::endl; // call myMax for char
return 0;
}
On compiling the code, compiler reports an error as show below. 编译代码时,编译器将报告错误,如下所示。
functionTemplates.cpp: In function ‘int main()’:
functionTemplates.cpp:18: error: no matching function for call to ‘myMax(int, int)’
functionTemplates.cpp:19: error: no matching function for call to ‘myMax(double, double)’
functionTemplates.cpp:20: error: no matching function for call to ‘myMax(char, char)’
I know that if i remove class U, compilation will be successful. 我知道,如果我删除U类,编译将成功。 But i want to know why does compiler bothers about an unused parameter? 但是我想知道为什么编译器会为一个未使用的参数烦恼?
The compiler cannot determine the type of the unused template argument. 编译器无法确定未使用的模板参数的类型。 You need to specify it explicitly, or remove the unused template argument. 您需要明确指定它,或删除未使用的模板参数。
For a general case, a compiler can determine the template parameters from: 对于一般情况,编译器可以从以下命令确定模板参数:
In your case, U
cannot be determined from the arguments used to make the function call since U
is not used by the arguments. 在你的情况, U
不能从用来做函数调用因为参数确定U
不使用的参数。 The only other way the compiler can determine U
is if it is used explicitly in the function call. 编译器确定U
的唯一其他方法是,是否在函数调用中显式使用它。 Eg 例如
std::cout << myMax<int, double>(3, 7) << std::endl;
PS It's not clear to me why you have U
as a template parameter in the first place. PS对我来说不清楚,为什么首先要使用U
作为模板参数。 It's not used at all. 根本不使用。 Won't it be easier to use: 使用起来会不会更容易:
template <class T>
T myMax(T x, T y)
{
return (x > y)? x: y;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.