Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nice way to declare enums in C++ without bloating the namespace

I noticed that if I do something like this in C++ using Microsoft Visual Studio Express 2013:

namespace LogLevelEnum {
enum Type {
    ALL,
    FINEST,
    FINE,
    INFO,
    WARNING,
    SEVERE,
    OFF
};
}
typedef LogLevelEnum::Type LogLevel;

I can access the enum items using things like LogLevel::INFO and LogLevel::WARNING, but not by simply doing INFO or WARNING. I like it that way because it doesn't put as many symbols into the encompassing namespace.

However, I was wondering whether or not this is standard behaviour. I know classes and namespaces can be indexed using the :: operator, but it makes a bit less sense for that to also work on enums, considering they simply dump everything in the namespace it's in.

like image 469
RPFeltz Avatar asked Sep 28 '22 06:09

RPFeltz


1 Answers

However, I was wondering whether or not this is standard behaviour.

Yes provided you are using a C++11 compliant compiler and by standard you are referring to the C++11 standard.

but not by simply doing INFO or WARNING.

This is because the enum is within the namespace scope. Have you tried LogLevelEnum ::INFO or LogLevelEnum ::WARNING?

Nice way to declare enums in C++ without bloating the namespace

Use Scoped enumerations i.e. enum struct | class instead of enum while defining the enum.

like image 154
Abhijit Avatar answered Oct 05 '22 07:10

Abhijit