Home » C++ » Extending enums in C++?

Extending enums in C++?

Posted by: admin November 30, 2017 Leave a comment

Questions:

Is there a way in C++ to extend/”inherit” enums?

I.E:

enum Enum {A,B,C};
enum EnumEx : public Enum {D,E,F};

or at least define a conversion between them?

Answers:

No, there is not.

enum are really the poor thing in C++, and that’s unfortunate of course.

Even the class enum introduced in C++0x does not address this extensibility issue (though they do some things for type safety at least).

The only advantage of enum is that they do not exist: they offer some type safety while not imposing any runtime overhead as they are substituted by the compiler directly.

If you want such a beast, you’ll have to work yourself:

  • create a class MyEnum, that contains an int (basically)
  • create named constructors for each of the interesting values

you may now extend your class (adding named constructors) at will…

That’s a workaround though, I have never found a satistifying way of dealing with an enumeration…

Questions:
Answers:

If you were able to create a subclass of an enum it’d have to work the other way around.

The set of instances in a sub-class is a subset of the instances in the super-class. Think about the standard “Shape” example. The Shape class represents the set of all Shapes. The Circle class, its subclass, represents the subset of Shapes that are Circles.

So to be consistent, a subclass of an enum would have to contain a subset of the elements in the enum it inherits from.

(And no, C++ doesn’t support this.)

Questions:
Answers:

I’ve solved in this way:

typedef enum
{
    #include "NetProtocols.def"
} eNetProtocols, eNP;

Of course, if you add a new net protocol in the NetProtocols.def file, you have to recompile, but at least it’s expandable.

Questions:
Answers:

http://www.codeproject.com/KB/cpp/InheritEnum.aspx goes over a method to created an expanded enum.

Questions:
Answers:

Just an idea:

You could try to create an empty class for each constant (maybe put them all in the same file to reduce clutter), create one instance of each class and use the pointers to these instances as the “constants”. That way, the compiler will understand inheritance and will perform any ChildPointer-to-ParentPointer conversion necessary when using function calls, AND you still get type-safety checks by the compiler to ensure no one passes an invalid int value to functions (which would have to be used if you use the LAST value method to “extend” the enum).

Haven’t fully thought this through though so any comments on this approach are welcome.

And I’ll try to post an example of what I mean as soon as I have some time.

Questions:
Answers:

The following code works well.

enum Enum {A,B,C};
enum EnumEx {D=C+1,E,F};