gpt4 book ai didi

c++ - 是什么让 enum -> int 比 enum -> unsigned 转换更好?

转载 作者:可可西里 更新时间:2023-11-01 18:35:58 26 4
gpt4 key购买 nike

在下面的代码中,选择了重载 f(int) 而不是 f(unsigned)。使用 clang 3.0 和 gcc 4.8 测试。

enum E
{
};

E f(int);
int f(unsigned);

E e = f(E(0));

我对标准的阅读使我认为 enum -> intenum -> unsigned 是相同的标准转换序列,它们都只包含一个整数转换。

[conv.integral] An rvalue of an enumeration type can be converted to an rvalue of an integer type.

根据[over.best.ics],仅包含整数转换的标准转换序列的等级是'Conversion'。

[over.ics.rank] Two implicit conversion sequences of the same form are indistinguishable conversion sequences unless one of the following rules apply: [...]

在比较两个标准转换序列时,所提到的规则似乎都不适用。

我错过了什么?

最佳答案

C++11:

[conv.prom]/3

A prvalue of an unscoped enumeration type whose underlying type is not fixed (7.2) can be converted to a prvalue of the first of the following types that can represent all the values of the enumeration (i.e., the values in the range b min to b max as described in 7.2): int, unsigned int, long int, unsigned long int, long long int, or unsigned long long int.

(强调我的)

然后,[over.ics.rank]/4:

Standard conversion sequences are ordered by their ranks: an Exact Match is a better conversion than a Promotion, which is a better conversion than a Conversion.

因此,对于表达式 f(E(0)) 的重载决议, 过载 E f(int);只需要积分提升(从 Eint ,通过 [conv.prom]),它具有更高等级的积分转换所需的 int f(unsigned); (从 Eunsigned 通过 [conv.integral])。


对于 C++03,论证是相同的,尽管第一个引用略有不同:[conv.prom]/2

An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2) can be converted to an rvalue of the first of the following types that can represent all the values of its underlying type: int, unsigned int, long, or unsigned long.

[over.ics.rank]/4 相同。

关于c++ - 是什么让 enum -> int 比 enum -> unsigned 转换更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17819109/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com