Templates and inheritance

J

Jim West

Can someone please explain to me why the following compiles:

class A {
public:
int d;
};

class B : public A {
public:
int e;
void f() { d = e; };
};



but if I make A and B templates it gives an error:

template <typename T>
class A {
public:
T d;
};

template <typename T>
class B : public A<T> {
public:
int e;
void f() { d = e; }; // error: identifier "d" is undefined
};


This occurs with GNU G++ and Intel ICC. Obviously I am missing a subtlety
of templates and/or inheritance. (I figured out that changing the line in
question to

void f() { A<T>::d = e; };

corrects the error, but I want understand why it is an error in the first
place.)
 
S

Salt_Peter

Can someone please explain to me why the following compiles:

class A {
public:
int d;

};

class B : public A {
public:
int e;
void f() { d = e; };

};

but if I make A and B templates it gives an error:

template <typename T>
class A {
public:
T d;

};

template <typename T>
class B : public A<T> {
public:
int e;
void f() { d = e; }; // error: identifier "d" is undefined

};

This occurs with GNU G++ and Intel ICC. Obviously I am missing a subtlety
of templates and/or inheritance. (I figured out that changing the line in
question to

void f() { A<T>::d = e; };

corrects the error, but I want understand why it is an error in the first
place.)

During two-phase name lookup, base classes depending on a template
argument are not considered. Recall that a member function has a
hidden this parameter.
So replace B::f() with a free function instead:

template< typename T >
void f( B<T>& r_b )
{
r_b.d = r_b.e;
}
 

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

Forum statistics

Threads
473,968
Messages
2,570,152
Members
46,697
Latest member
AugustNabo

Latest Threads

Top