4

Given this popular solution for "enum inheritance" (probably better called "extension"), would it be possible to raise a compiler error if I redefine an enumerator identifier of the base class in the derived class?

Example:

struct Enum
{
    enum
    {
        One = 1,
        Two,
        _last
    };
};

struct EnumDeriv : Enum
{
    enum
    {
        Three = Enum::_last,
        Four,
        One  //<--- this compiles but I'd like to get a compiler error instead 
    };
};

Live Demo

What happens here is that EnumDeriv::One masks (is this the right term?) the definition of Enum::One. So EnumDeriv::One will now map to the "unexpected" integer value of 5.

This could create some hard-to-debug errors if we derive from Enum and inadvertently redefine some of its enumerator identifiers.

Any solutions of how to turn the "masking" into a compiler error or a suggestion for a similarly elegant "enum inheritance" solution that does not have this potential source of error would be welcome.

Community
  • 1
  • 1
zett42
  • 25,437
  • 3
  • 35
  • 72
  • Hmm.. I thought I'd be smart and use C++11 strongly typed enums (IE: `enum class foo {...}; enum class bar : foo {...};` didn't work. lol. – Brandon Mar 22 '17 at 00:41
  • This doesn't have to model an "is a" relationship, does it? Basically you want to reuse the enumerations defined in another enum and ideally also be able to convert between them? – Daniel Jour Mar 22 '17 at 01:35
  • Well, same happens with struct members. [Prevent derived classes from hiding non-virtual functions from base](http://stackoverflow.com/questions/14997210/prevent-derived-classes-from-hiding-non-virtual-functions-from-base) – Michael Nastenko Mar 22 '17 at 02:48
  • _reuse the enumerations defined in another enum and ideally also be able to convert between them_ ... yep! Use case is a map index that can be extended by derived classes. – zett42 Mar 22 '17 at 07:48

0 Answers0