让我们考虑以下代码:
#include <type_traits>
enum class foo_bar : unsigned
{
foo,
bar,
};
int main()
{
foo_bar bar = foo_bar::bar;
// unsigned a = bar; -- error: cannot convert ‘foo_bar’ to ‘unsigned int’ in initialization
unsigned a = static_cast<std::underlying_type<foo_bar>::type>(bar);
return 0;
}
为什么不允许隐式转换?基础类型是已知的,a
的类型与foo_bar
基础类型匹配。隐式转换似乎是安全的,可以在不丢失信息的情况下执行。为什么从语言设计的角度来看演员是必要的?
答案 0 :(得分:4)
从N2347开始,隐式整数提升的问题在于您可以比较两个不同的枚举:
enum Color { ClrRed, ClrOrange, ClrYellow, ClrGreen, ClrBlue, ClrViolet };
enum Alert { CndGreen, CndYellow, CndRed };
Color c = ClrGreen;
Alert a = CndGreen;
bool armWeapons = ( a >= c ); // compiles but does not make sense
要了解这里的实际情况,您可以使用结构模拟枚举类:
struct A {
operator int() const {
// for simplicity, just return fixed value
return 1;
}
};
struct B {
operator int() const {
return 2;
}
};
A a;
B b;
int i = b; // ok
bool x = (a < b); // yay, this compiles
现在,正确的解决方案是创建运算符explicit
:
struct B {
explicit operator int() const {
return 2;
}
};
A a;
B b;
bool x = (a < b); // finally does not work
int i = b; // but now this does not work without explicit cast either