Skip to content

Instantly share code, notes, and snippets.

@iscgar
Created August 2, 2015 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iscgar/c18e308b98bee9752754 to your computer and use it in GitHub Desktop.
Save iscgar/c18e308b98bee9752754 to your computer and use it in GitHub Desktop.
"Inheritable" enums
#include <iostream>
struct BaseEnum
{
public:
operator int() const { return this->type_; }
protected:
inline BaseEnum(int type) : type_(type) {}
private:
int type_;
};
struct DefaultEnumValue : public BaseEnum
{
public:
inline DefaultEnumValue() : BaseEnum(0) {}
};
struct ExtendedEnum : public BaseEnum
{
enum EExtendedEnum
{
FirstValue,
SecondValue
};
explicit inline ExtendedEnum(EExtendedEnum type) : BaseEnum(static_cast<int>(type)) {}
};
int main()
{
std::cout << "DefaultEnumValue value: " << DefaultEnumValue() << " (" << sizeof(DefaultEnumValue) << " bytes)" << std::endl;
std::cout << "ExtendedEnum::SecondValue value: " << ExtendedEnum(ExtendedEnum::SecondValue) << " (" << sizeof(ExtendedEnum) << " bytes)" << std::endl;
return 0;
}
@iscgar
Copy link
Author

iscgar commented Aug 2, 2015

The basic idea can be extended into an even more horrifying code, such as:

struct ExtendedEnum : public BaseEnum
{
    enum EExtendedEnum
    {
        FirstValue,
        SecondValue
    };

    explicit inline ExtendedEnum(EExtendedEnum type) : BaseEnum(static_cast<int>(type)) {}

protected:
    inline ExtendedEnum(int type) : BaseEnum(type + SecondValue + 1) {}
};

struct EvenMoreExtendedEnum : public ExtendedEnum
{
    enum EEvenMoreExtendedEnum
    {
        FirstValue,
        SecondValue
    };

    explicit inline EvenMoreExtendedEnum(EEvenMoreExtendedEnum type) : ExtendedEnum(static_cast<int>(type)) {}
};

But that's just evil.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment