Template question

P

piffpuff123

Hello!
I have a type defined in a subclass, and I'd like to use it in the
base class. I tried this but it doesn't work:

template <class T> struct Base {
typename T::Type x;
};

struct Derived: public Base<Derived> {
typedef int Type;
};

It seems ok to me.. Why doesn't it work, and what should I do instead?
Thanks!
 
V

Victor Bazarov

I have a type defined in a subclass, and I'd like to use it in the
base class. I tried this but it doesn't work:

template <class T> struct Base {
typename T::Type x;
};

struct Derived: public Base<Derived> {

The trouble here is that 'Derived' is used before being fully defined.
Unfortunately you're SOL in this case. You need to either pass your
'int' explicitly to 'Base' or use the third class/template for both
'Base::x' and 'Derived::Type' (commonly known as "type traits idiom").
typedef int Type;
};

It seems ok to me.. Why doesn't it work, and what should I do instead?

See above.

V
 
A

Alf P. Steinbach

* (e-mail address removed):
Hello!
I have a type defined in a subclass, and I'd like to use it in the
base class. I tried this but it doesn't work:

template <class T> struct Base {
typename T::Type x;
};

struct Derived: public Base<Derived> {
typedef int Type;
};

It seems ok to me.. Why doesn't it work

Type Derived is incomplete at the time the Base::x declaration is analyzed.

You could do that in a member function of Base, but not directly in the
Base class definition.

, and what should I do instead?

template <class T> struct Base { typename T::Type x; };
struct X { typedef int Type; };
struct Derived: public X, public Base<X> {};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top