views:

41

answers:

2

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;
}
+3  A: 

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; 
} 
Chubsdad
Any way to do this without inheritance?
Steve Townsend
why, what issue does *private* inheritence cause?
jk
@jk - none, just curious.
Steve Townsend
+2  A: 

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.,

Alf P. Steinbach
@Alf - yes this is Microsoft C++ in VS2010, added this tag to the q
Steve Townsend
@Alf - when I make the suggested change, the `cout` line does not compile. error C2039: 'X' : is not a member of 'B<T>' with [ T=A ]
Steve Townsend
Alf P. Steinbach
@Alf - that comment is the clarification I needed - thanks
Steve Townsend