Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum class underlying type with forward declaration

Tags:

c++

enums

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...

like image 993
Epic Avatar asked Mar 17 '26 05:03

Epic


1 Answers

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.

like image 124
ネロク・ゴ Avatar answered Mar 22 '26 02:03

ネロク・ゴ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!