HighCommander4
HighCommander4

Reputation: 52799

Exposing base class enum without tediously listing enumerators

In C++11, I can expose an enumerator which is protected in a base class, to users of a derived class, as follows:

class Base
{
protected:
    enum Waldo { hidden, found };
};

class Derived : public Base
{
public:
    using Base::Waldo;
}

void foo()
{
    Derived::Waldo w = Derived::Waldo::found;
}

Unfortunately, in C++03, Derived::Waldo::found is illegal, and Derived::found is met with 'Base::Waldo Base::found' is protected within this context.

I could work around that by also writing a using for each enumerator:

class Derived : public Base
{
public:
    using Base::Waldo;
    using Base::hidden;
    using Base::found;
}

void foo()
{
    Derived::Waldo w = Derived::found;  // works in C++03
}

but this can be really tedious to do if the enumerator has many enumerators. Is there a way to pull off this enum-exposing in C++03 without this tedium?

Upvotes: 2

Views: 791

Answers (2)

Eternal
Eternal

Reputation: 2959

Well, I think there are lots of different ways to do this, depending on what you want to do with the enum. Here is one:

struct WaldoStates
{
    enum States{hidden, found};
};

class Base
{
public:
    typedef WaldoStates Waldo;
};

class Derived : public Base
{
};

void foo()
{
    WaldoStates::States state = Derived::Waldo::found;
}

Now, this is good if simply want the states to be accessible with something like myClass::Waldo::hidden in any class of the inheritance tree. If you want to be able to set different states for some of the derived classes, you may want to do something like this instead:

struct WaldoStates
{
    typedef int State;
};

struct DefaultWaldoStates : public WaldoStates
{
    enum States{hidden, found};
};

 struct OtherWaldoStates : public WaldoStates
{
    enum States{stillHidden, alreadyFound};
};

class Base
{
public:
    typedef DefaultWaldoStates Waldo;
};

class Derived : public Base
{
};

class OtherDerived : public Base
{
public:
    typedef OtherWaldoStates Waldo;
};

void foo()
{
    WaldoStates::State state0 = Derived::Waldo::found;
    WaldoStates::State state1 = OtherDerived::Waldo::alreadyFound;
}

Upvotes: 0

Columbo
Columbo

Reputation: 60999

SCNR!

struct Wrap
{
    enum Waldo { hidden, found };
};

class Base : protected Wrap
{
};

class Derived : public Base
{
public:
    using Base::Wrap;
};

void foo()
{
    Derived::Wrap::Waldo w = Derived::Wrap::found;
}

Edit: Or you put it inside:

class Base
{
protected:

    struct Wrap
    {
        enum Waldo { hidden, found };
    };
};

class Derived : public Base
{
public:
    using Base::Wrap;
};

void foo()
{
    Derived::Wrap::Waldo w = Derived::Wrap::found;
}

Upvotes: 1

Related Questions