C++ 中此示例的函数重载中的歧义解释;

发布于 2024-09-06 23:17:04 字数 347 浏览 4 评论 0原文

我正在阅读 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

妄司 2024-09-13 23:17:04

从上面的 int 得到的任何东西都不再是促销了。任何小于 int 到 int 的值都是升级(极少数情况除外 - 见下文)

因此,如果您更改为以下内容,它就会变得明确,选择第一个

void f1(int);
void f1(long);

void k(unsigned short i) {
    f1(i);
}

注意,这仅在 int< 的平台上才正确/code> 可以存储所有unsigned Short 的值。在情况并非如此的平台上,这不会是促销,并且调用是不明确的。在此类平台上,unsigned int 类型将成为升级目标。

浮点也会发生同样的事情。将 float 转换为 double 是一种提升,但将 double 转换为 long double 则不是一种提升。在这种情况下,C++ 与 C 不同,其中 doublelong 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

void f1(int);
void f1(long);

void k(unsigned short i) {
    f1(i);
}

Notice that this is only true on platforms where int can store all values of unsigned short. On platforms where that is not the case, this won't be a promotion and the call is ambiguous. On such platforms, the type unsigned int will be the promotion target.

Sort of the same thing happens with floating points. Converting float to double is a promotion, but double to long double isn't a promotion. In this case, C++ differs from C, where double to long double is a promotion likewise (however, it doesn't have overloading anyway).

愛上了 2024-09-13 23:17:04

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文