Inheritance with templates?

S

saneman

In the below non-template example a subclass BOB returns a protected
field from a super class POP:


class POP {
protected:
int blop;
};



class BOB : public POP {
public:
int size () {return blop;}
};


If I declared them as templates I get an error:

template <class A>
class POP {
protected:
int blop;
};

template <typename A, typename B = POP<A> >
class BOB : public B {
public:
int size () {return blop;}
};


error: ‘blop’ was not declared in this scope

It only works if it change the size() function to:

int size () {return B::blop;}

But I can also change it to:

int size () {return A::blop;}

even though I don't make sense, but the compiler does not complain.

When is it necessary to qualify inherited fields when using templates?
 
L

ltcmelo

In the below non-template example a subclass BOB returns a protected
field from a super class POP:

class POP {
protected:
int blop;

};

class BOB : public POP {
public:
int size () {return blop;}

};

If I declared them as templates I get an error:

template <class A>
class POP {
protected:
int blop;

};

template <typename A, typename B = POP<A> >
class BOB : public B {
public:
int size () {return blop;}

};

error: 'blop' was not declared in this scope

It only works if it change the size() function to:

int size () {return B::blop;}

But I can also change it to:

int size () {return A::blop;}

even though I don't make sense, but the compiler does not complain.

When is it necessary to qualify inherited fields when using templates?


Basically because C++ rules say that non-dependent names should not be
looked up in dependent base classes (which is your case). You could
also use "this->blop" or "using B::blop" to avoid the compilation
error. Please, take a look at this faq: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.19
 

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,968
Messages
2,570,152
Members
46,697
Latest member
AugustNabo

Latest Threads

Top