Rohit Jain
Rohit Jain

Reputation: 3

Cannot compile code using an enum declared in a templated base class [C++]

The following code (included in a single header file) is simple demonstration of the problem I encounter:

template <class T>
class A
{
public:
    enum Type
    {
        ONE,
        TWO
    };

    A( Type tp = ONE ):tp(tp) {

    }

protected:
    Type tp;
};

template <class T>
class B : public A<T>
{

    B( Type _tp ):A<T>(_tp) {

    }

};

This produces the compilation error (in Clang)

Untitled 2.cpp:24:4: error: unknown type name 'Type'
        B(Type _tp ):A<T>(_tp) {
          ^
1 error generated.

If I instead move the enum outside the scope of A, or remove the templatization of A and B, then the above code compiles.

Upvotes: 0

Views: 58

Answers (1)

jwimberley
jwimberley

Reputation: 1748

If your enum is going to be that simple, it would probably be best to simply move it outside A<T>, as you already indicated worked -- you could keep it in a namespace if you'd like. Otherwise, the enum is inside the class A<T> and so inside B, Type in an incomplete name. Instead,

template <class T>
class B : public A<T>
{

    B( typename A<T>::Type _tp )
      : A<T>(_tp)
    {
    }

};

The typename keyword is required because A is templated.

Upvotes: 2

Related Questions