Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template class and inheritance [duplicate]

Possible Duplicates:
[FAQ] Why doesn't a derived template class have access to a base template class' identifiers? Problem with protected fields in base class in c++
cannot access data member in a class template

Following code gives me compilation error. What is wrong?

struct Base {
   int amount;
};

template<class T> struct D1 : public Base {
};

template<class T>
struct D2 : D1<T> {
  void foo() { amount=amount*2; /* I am trying to access base class data member */ };
};

int main() {
  D2<int> data;
};


test.cpp: In member function 'void D2<T>::foo()':
test.cpp:11: error: 'amount' was not declared in this scope

How to fix this?

thanks

like image 616
anon Avatar asked Feb 07 '11 08:02

anon


People also ask

Can template class be inherited?

Inherited Member Functions of Class Templates are not Available.

Can a template class inherit from another template class?

It is possible to inherit from a template class. All the usual rules for inheritance and polymorphism apply. If we want the new, derived class to be generic it should also be a template class; and pass its template parameter along to the base class.

What is the difference between Typename and class in template?

There is no difference between using <typename T> OR <class T> ; i.e. it is a convention used by C++ programmers.

What is the diamond problem in inheritance?

The "diamond problem" (sometimes referred to as the "Deadly Diamond of Death") is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C.


1 Answers

The problem here has to do with how names are looked up in template classes that inherit from template base classes. The actual rules behind it are pretty arcane and I don't know them off the top of my head; I usually have to consult a reference to learn precisely why this doesn't work.

The way to fix this is to explicitly prefix the member you're accessing with this->:

void foo() { 
    this->amount = this->amount * 2; // Or: this->amount *= 2;
}

This gives the compiler an unambiguous hint about where the name amount comes from and should resolve the compiler error.

If someone wants to give a more detailed description of why this error occurs I'd love to see a good explanation.

like image 190
templatetypedef Avatar answered Sep 21 '22 08:09

templatetypedef