C++ 中此示例的函数重载中的歧义解释;
我正在阅读 Stroustrup 的书,其中有关重载和相关歧义的部分。
有一个例子如下:
void f1(char);
void f1(long);
void k(int i)
{
f1(i); //ambiguous: f1(char) or f1(long)
}
正如评论所述,调用是不明确的。 为什么?
本书的前一节阐述了基于形式参数和实际参数匹配的 5 条规则。那么上面的函数调用不应该属于关于“促销”的规则 2 吗? 我的猜测是“i”应该提升为 long,仅此而已。
根据评论,似乎 int 到 char 的转换(降级?)也符合规则 2?
I'm reading Stroustrup's book, the section on overloading and related ambiguities.
There's an example as follows:
void f1(char);
void f1(long);
void k(int i)
{
f1(i); //ambiguous: f1(char) or f1(long)
}
As the comment states, the call is ambiguous.
Why?
The previous section in the book stated 5 rules based on matching formal and actual parameters. So shouldn't the above function call come under rule 2, regarding "promotions"?
My guess was that 'i' should be promoted to a long, and that's that.
As per the comment, it seems that a int to char conversion (a demotion?) also comes under rule 2?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从上面的 int 得到的任何东西都不再是促销了。任何小于 int 到 int 的值都是升级(极少数情况除外 - 见下文)
因此,如果您更改为以下内容,它就会变得明确,选择第一个
注意,这仅在
int< 的平台上才正确/code> 可以存储所有
unsigned Short
的值。在情况并非如此的平台上,这不会是促销,并且调用是不明确的。在此类平台上,unsigned int
类型将成为升级目标。浮点也会发生同样的事情。将
float
转换为double
是一种提升,但将double
转换为long double
则不是一种提升。在这种情况下,C++ 与 C 不同,其中double
到long double
同样是一种提升(但是,它没有重载)。Anything goint from int above isn't a promotion anymore. Anything going less than int to int is a promotion (except for rare cases - see below)
So if you change to the following it becomes non-ambiguous, choosing the first one
Notice that this is only true on platforms where
int
can store all values ofunsigned short
. On platforms where that is not the case, this won't be a promotion and the call is ambiguous. On such platforms, the typeunsigned int
will be the promotion target.Sort of the same thing happens with floating points. Converting
float
todouble
is a promotion, butdouble
tolong double
isn't a promotion. In this case, C++ differs from C, wheredouble
tolong double
is a promotion likewise (however, it doesn't have overloading anyway).int 可以转换为 char,int 也可以转换为 long。
因此,从这个意义上说,它是不明确的,因为编译器无法判断您正在调用哪个。
An int can be converted to a char, and a int can also be converted to a long.
So in that sense it is ambiguous, as the compiler cannot tell which you're calling.