Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum scoping issues

Tags:

c++

scope

enums

I try to keep things as local as possible, so I put enums at class scope, even if they are shared between two classes (I put it in the class that "goes better" with it.) This has worked out great, but I recently ran into an issue where a circular dependency will occur if I put the enum at class scope.

The enum is going to be a constructor argument for multiple classes, and the class it is in (and the class that makes the most sense for it to be in) includes those classes. Thus, it isn't possible to use the enum as a constructor argument for the classes included because it will result in a circular dependency.

Would it be better to just put this enum in its own header file, and if so, should I put all of the enums in the header file to be consistent? Are there any other solutions to this issue (that are logical)?

like image 603
Anonymous Avatar asked Nov 15 '09 17:11

Anonymous


1 Answers

Since C++11, you can use an enum class (or enum struct - the same thing, declared differently), where the enum values are scoped to the enum's name. For example, here is a valid C++11 declaration.

enum class token_type {
    open_paren,
    close_paren,
    identifier
};

To access the values of the enum, however, you must scope it correctly using the :: operator. Hence, this is a valid assignment in C++11:

token_type type = token_type::close_paren;

But this is not:

token_type type = close_paren;

This solves the naming conflict, and means you don't have to use container namespace or struct just to stop the scope of the values leaking to where they shouldn't. This means that the following enum can exist in the same scope as token_type:

enum class other_enum {
    block,
    thingy,
    identifier
};

Now the two values called identifier in the two different structs will not interfere.

like image 69
Tom Galvin Avatar answered Sep 25 '22 09:09

Tom Galvin