为什么编译器不解析对模板函数的调用?
在下面的程序中,为什么编译器会为调用 printMax
模板函数而不是调用 printMaxInts
函数生成错误?
#include <iostream>
template<class A>
void printMax(A a,A b)
{
A c = a>b?a:b;
std::cout<<c;
}
void printMaxInts(int a ,int b)
{
int c = a>b?a:b;
std::cout<<c;
}
int main()
{
printMax(1,14.45);
printMaxInts(1,24);
}
In below program why does the compiler generate an error for the call to the printMax
template function and not the call to the printMaxInts
function?
#include <iostream>
template<class A>
void printMax(A a,A b)
{
A c = a>b?a:b;
std::cout<<c;
}
void printMaxInts(int a ,int b)
{
int c = a>b?a:b;
std::cout<<c;
}
int main()
{
printMax(1,14.45);
printMaxInts(1,24);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了让编译器从传递给函数模板的参数中推导出模板参数
A
,两个参数a
和b
都必须具有相同类型。您的参数的类型为
int
和double
,因此编译器无法推断出它应实际用于A
的类型。A
应该是int
还是应该是double
?您可以通过使两个参数具有相同的类型来解决此问题:
或者通过显式指定模板参数:
可以调用对非模板函数的调用的原因是编译器不需要推导参数的类型:它知道参数的类型,因为您在函数声明中说了它们的内容:
a
和b
都是int
类型。当您将double
作为参数传递给此函数时,double ->对参数执行 int
标准转换,并使用结果int
调用该函数。In order for the compiler to deduce the template parameter
A
from the arguments passed to the function template, both arguments,a
andb
must have the same type.Your arguments are of type
int
anddouble
, and so the compiler can't deduce what type it should actually use forA
. ShouldA
beint
or should it bedouble
?You can fix this by making both arguments have the same type:
or by explicitly specifying the template parameter:
The reason that the call to the non-template function can be called is that the compiler does not need to deduce the type of the parameters: it knows the type of the parameters because you said what they were in the function declaration:
Both
a
andb
are of typeint
. When you pass adouble
as an argument to this function, thedouble -> int
standard conversion is performed on the argument and the function is called with the resultingint
.以下代码基于詹姆斯的答案。您会注意到我已经取出了条件表达式:我这样做是因为该表达式的结果子句必须具有相同的类型,这对 A 和 B 施加了额外的限制。
对 A 和 B 的唯一要求此版本的代码是有一个与它们相关的运算符<()(或者可以将一个运算符转换为另一个),并且存在必需的运算符<<()函数。
The following code builds on James's answer. You'll notice that I've taken out the conditional expression: I've done this because the result clauses to that expression must have the same type, which imposes an additional restriction on A and B.
The only requirements on A and B in this version of the code is that there's an operator<() that related them (or one can be converted to the other), and that the requisite operator<<() functions exist.