开发者

Anonymous enum classes

Is is possible to write a anonymous enum class and then comparing what it contains? Eg.

enum clas开发者_高级运维s { APPLE, BANANA } fruitType;
// ...
if (fruitType == fruitType::APPLE)
    // ...


No, fruitType is a variable (despite Type in the name). You cannot use a variable name to access things about its type.

The idea with enum class is that the values are not visible outside the definition unless you prefix them with the type name. If the type doesn't have a name, this will be difficult!


I'd say this doesn't make sense. It breaks the whole idea of the enum class, which was introduced to solve some of the problems of the traditional enums (export of enumerators to the surrounding scope, implicit conversion to int, impossibility to specify the underlying type). If you declare an anonymous enum class, its enumerators are not accessible, since they cannot be qualified. So it doesn't make any sense.


You can't do this:

enum class { APPLE, BANANA } fruitType;
if (fruitType == fruitType::APPLE)

But you can do this:

enum class FT { APPLE, BANANA } fruitType;
if (fruitType == FT::APPLE)

...which is probably just as easy.


Note, that you probably want to initialize it:

enum class FT { APPLE, BANANA } fruitType = FT::BANANA;
if (fruitType == FT::APPLE)


You can't.

But I agree that it would be nice to be able to do this. Sometimes the enum is already part of a sufficiently nested and limited scope and further qualification would be pure overkill, yet you would still like to prohibit conversion-to-int. So you have to make a trade-off: choose both features or neither.


Not this way. fruitType::APPLE is incorrect, as fruitType is not the name of a namespace. However, if you simply write fruitType == APPLE (without prefixing APPLE), then it's fine.


Yes this is possible. But if it's anonymous then, it won't be accessible outside its whatever scope.

Edit: Your second part of the question is an error. You don't have to mention fruitType::. However even after removing it; compilation fails. Which depicts that, it's not usable.

So I am not sure about your second question. I had asked a similar question long back.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜