Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define an extensible C++ enum system [duplicate]

I have encounter a problem in my project on enums. In EventDef.h,

enum EventDef {
    EVT1 = 0,
    EVT2,
    EVT3,
    EVT_NUM,
}

In this way, I can extend the EventDef system in another header UIEventDef.h by

#include "EventDef.h"
enum UIEventDef {
    UIEVT1 = EVT_NUM,
    UIEVT2,
    UIEVT3,
}

But, there is a limitation that i can not do this in NetEvent.h the same way.

#include "EventDef.h"
enum NetEventDef {
    NETEVT1 = EVT_NUM,
    NETEVT2,   //wrong: this will have the same value as UIEVT2
    NETEVT3,  
}

Is there a better compile time solution in C++ such as templates that can help ?

like image 429
rechardchen Avatar asked Jun 01 '26 04:06

rechardchen


1 Answers

The idea of extensible enums is not inherently "bad design". In other languages there is a history of them, even if c++ does not support them directly. There are different kinds of extensibility.

Things that extensible enums would be useful for

  • error codes
  • message types
  • device identification (OIDs are a hierarchical enum like system)

Examples of enum extensibility

  • Objective Modula Two has enums that are extensible with a class like inheritance.
  • The Extensible Enum Pattern in Java, which can be implemented in c++.
  • Java enums are extensible in that extra data and methods can be a part of an enum.
  • In c++, the typeid operator is essentially a compiler generated enum with attached values.

The kind of extensibility you showed in your sample code does not have an elegant implementation in unaided c++. In fact, as you pointed out, it easily leads to problems.

Think about how you are wanting to use an extensible enum. Perhaps a set/map of immutable singleton objects will meet your needs.

Another way to have extensible enums in c++ is to use a code generator. Every compilation unit that wants to add to an extensible enum, records the ids in its own, separate, .enum file. At build time, before compilation, a script (ie perl, bash, ...) looks for all .enum files, reads them, assigns numeric values to each id, and writes out a header file, which is included like any other.

like image 170
walrii Avatar answered Jun 03 '26 21:06

walrii



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!