我在编程的时候发现了一些有趣的事情:
enum class Foo {
FOO_THING,
FOO_TOO
};
int main() {
Foo foo{1}; // It is OK
Foo foo2(1); // It is an invalid
}
你能告诉我,为什么 foo{1}
对于编译器来说是可以的,而为什么 foo2(1)
是无效的?
编译器 GCC (g++ (Ubuntu 7.3.0-21ubuntu1~16.04) 7.3.0
) 说:
$ g++ -Wall -std=c++17 foo.cpp
error: cannot convert ‘int’ to ‘Foo’ in initialization
Foo foo2(1);
我真的很想知道底层机制。 :)))
编辑:可能是一些编译器错误...
最佳答案
C++17 特定 documentation有以下花括号初始化器
Otherwise, if T is a enumeration type that is either scoped or unscoped with fixed underlying type, and if the braced-init-list has only one initializer, and if the conversion from the initializer to the underlying type is non-narrowing, and if the initialization is direct-list-initialization, then the enumeration is initialized with the result of converting the initializer to its underlying type.
所以 foo
似乎符合有效的 C++17,但是 foo2
没有被初始化是无效的。
关于c++ - 使用 int 进行枚举类初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50717751/