Epic
Epic

Reputation: 622

enum class underlying type with forward declaration

I have a small enum class which I would like to forward declare in a few places. Is there a way to decouple the base type from the forward declaration? I am afraid that at some later point someone will change the type.

for example I have the enum

enum class e_mode : bool
{
     SYNC,
     ASYNC
};

the forward declaration will be:

enum class e_mode : bool;

if someone adds another value he will need to change the bool to char and then go around changing the forward declarations. I would like to avoid that...

Upvotes: 2

Views: 2231

Answers (2)

Luka Rahne
Luka Rahne

Reputation: 10447

You can have a ".h" file that defines only forward declaration of enum. Insted of forward declaring enum, you then include this "cheap" h file.

Upvotes: 1

jfMR
jfMR

Reputation: 24738

The enum's underlying type could be previously defined by means of typedef:

typedef bool e_mode_base_t;

Then, you can use this type for the enum's forward declaration:

enum class e_mode: e_mode_base_t;

and for the enum's definition as well:

enum class e_mode : e_mode_base_t
{
     SYNC,
     ASYNC
};

This way, you only need to modify the definition of e_mode_base_t when you wish to change the enum's underlying type.

You could as well create a type alias by means of using instead of typedef:

using e_mode_base_t = bool;

which may be more readable.

Upvotes: 7

Related Questions