Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strongly typed enums without explicit scoping?

Tags:

c++

enums

c++11

I want strong enum types. C++0x has this feature but unfortunately they also require explicit scoping:

enum class E {e1, e2, e3};
E x = E::e1; //OK
E y = e1; //error

Sometimes this is desirable, but sometimes it's just unnecessarily verbose. The identifiers might be unique enough by themselves or the enum might already be nested inside a class or namespace.

So I'm looking for a workaround. What would be the best way to declare the enum values also in the surrounding scope?

like image 546
Timo Avatar asked Aug 08 '11 07:08

Timo


People also ask

Are enums strongly typed?

Enum Class C++11 has introduced enum classes (also called scoped enumerations), that makes enumerations both strongly typed and strongly scoped.

Are enums slow python?

Unfortunately big IntFlag enums are extremely slow in combining attributes - I thought of using them instead of frozensets (reduce memory) but or'ing a few hundred int flags takes a lot of time when an IntFlag has ~10k members.

What is a scoped enum?

Overview. Scoped enums (enum class/struct) are strongly typed enumerations introduced in C++11. They address several shortcomings of the old C-style (C++98) enums, mainly associated with type-safety and name collisions.

Do enums always start at 0?

Numeric EnumsEnums don't always start with 0. We can define enums as numbers during initialization.


1 Answers

If you want the values visible in the surrounding scope, just add a couple of constants:

enum class E {e1, e2, e3};

const E e1 = E::e1;
const E e2 = E::e2;
const E e3 = E::e3;
like image 71
Bo Persson Avatar answered Sep 21 '22 01:09

Bo Persson