c++ – typedef for enum from template base class – Education Career Blog

Followup on an answer from last night – I was hoping more comments would answer this for me but no dice.

Is there a way to achieve this without inheritance that does not require the cumbersome usage in the penultimate line of code below, which writes the value to cout?

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;
}

,

Does this help?

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

template <class T> 
struct B : private T{    // private inheritance.
public: 
    using T::X; 
}; 

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

,

The only way to place names enum value names directly into a class, is by inheriting from a class with those names.

The code you’re showing seems to use a Microsoft language extension.

In C++98 an enum typename can not be used to qualified one of the value names:

Comeau C/C++ 4.3.10.1 (Oct  6 2008 11:28:09) for ONLINE_EVALUATION_BETA2
Copyright 1988-2008 Comeau Computing.  All rights reserved.
MODE:strict errors C++ C++0x_extensions

"ComeauTest.c", line 17: error: name followed by "::" must be a class or namespace
          name... Wild guess: Did you #include the right header?
      std::cout << B<A>::E::X << std::endl;
                         ^

1 error detected in the compilation of "ComeauTest.c".

So instead of …

typedef typename T::E E;

… do …

typedef T E;

Cheers & hth.,

Leave a Comment