c++ – something like a using declaration for enums? – Education Career Blog

Basically this is what I’d like to do:

struct A {
    enum E {
        X, Y, Z
    };
};

template <class T>
struct B {
    using T::E;
};

// basically "import" the A::E enum into B.
std::cout << B<A>::X << std::endl;

The reason why is that I want to basically inject the implementation details into my template class. At the same time, the enum of the “model” reflects information that I want the user to be able to have for a particular instantiation of a template. Is this possible?

I know that I could have B inherit from A, but I think that isn’t an ideal solution because I want to be able to add new “models” without changing the guts of B.

EDIT: Now that I’ve though about it, inheritance doesn’t necessarily need to be ruled out. Perhaps the following is ideal:

struct A {
    enum E {
        X, Y, Z
    };
};

template <class T>
struct B : A {
};

int main() {
    std::cout << B<A>::X << std::endl;
}

,

This works for me:

struct A {
    enum E {
        X, Y, Z
    };
};

template <class T>
struct B {
    typedef typename T::E E;
};

// basically "import" the A::E enum into B.
int main(void)
{
    std::cout << B<A>::E::X << std::endl;
    return 0;
}

Output is

0

I do get a warning about non-standard extension in that qualified name so perhaps there is a more elegant solution.

,

I think you can do

template <class T>
struct B {
    typedef typename T::E E;
};

Leave a Comment