【发布时间】:2019-11-19 13:07:33
【问题描述】:
考虑下面这段代码
#include <iostream>
using namespace std;
enum myEnum { a, b, c };
void test(myEnum e) {
cout << "myEnum overload" << endl;
}
void test(unsigned int i) {
cout << "unsigned int overload" << endl;
}
int main() {
test(a);
test(1);
test(1u);
return 0;
}
(我知道enum class 在这种情况下比enum 更安全,但我使用的是具有旧式枚举的开源代码。)
当我用 g++ 4.4.7 编译并运行它时,我得到了
myEnum overload
unsigned int overload
unsigned int overload
即编译器更喜欢将int 转换为unsigned int 而不是将其转换为myEnum。这就是我想要的,但我想知道这是否总是得到保证。该标准没有具体说明myEnum 的底层类型应该是什么,所以我想如果它恰好是int,也许这会比unsigned int 更受青睐。
但是当我注释掉 unsigned int 重载时,我得到了这个错误:
enum_overload.cpp: In function ‘int main()’:
enum_overload.cpp:17: error: invalid conversion from ‘int’ to ‘myEnum’
enum_overload.cpp:17: error: initializing argument 1 of ‘void test(myEnum)’
enum_overload.cpp:18: error: invalid conversion from ‘unsigned int’ to ‘myEnum’
enum_overload.cpp:18: error: initializing argument 1 of ‘void test(myEnum)’
这是否意味着旧式枚举隐式地将 转换为 它们的基础类型,而不是 从 那些类型?如果是这种情况,那么这将回答我之前的问题:如果整数类型不能转换为myEnum,那么重载决议的行为就可以保证如上。
【问题讨论】:
标签: c++ enums implicit-conversion overload-resolution