Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance and templates in C++ - why are inherited members invisible?

Tags:

When a template publicly inherits from another template, aren't the base public methods supposed to be accessible?

template <int a> class Test { public:     Test() {}     int MyMethod1() { return a; } };  template <int b> class Another : public Test<b> { public:     Another() {}     void MyMethod2() {         MyMethod1();     } };  int main() {     Another<5> a;     a.MyMethod1();     a.MyMethod2(); } 

Well, GCC craps out on this... I must be missing something totally obvious (brain melt). Help?

like image 964
OldCoder Avatar asked Oct 14 '09 17:10

OldCoder


People also ask

Can template class be inherited?

Class Template Inheritance in C++Inheriting from a template class is feasible. All regular inheritance and polymorphism rules apply. If we need the new derived class to be general, we must make it a template class with a template argument sent to the base class.

Is inheritance better than templates?

Templates provide sortability in a much nicer way, since the sortee doesn't need to know that it's being sorted. Complex inheritance typically results when you work with a forced mindset that everything must be an inheritance hierarchy, which is in fact rarely appropriate.

Can a template class be derived from a non template class?

Deriving from a non-template base classIt is quite possible to have a template class inherit from a 'normal' class. This mechanism is recommended if your template class has a lot of non-template attributes and operations. Instead of putting them in the template class, put them into a non-template base class.


1 Answers

This is part of the rules concerning dependent names. Method1 is not a dependent name in the scope of Method2. So the compiler doesn't look it up in dependent base classes.

There two ways to fix that: Using this or specifying the base type. More details on this very recent post or at the C++ FAQ. Also notice that you missed the public keyword and a semi-colon. Here's a fixed version of your code.

 template <int a> class Test { public:     Test() {}     int MyMethod1() { return a; } };  template <int b> class Another : public Test<b> { public:     Another() {}     void MyMethod2() {         Test<b>::MyMethod1();     } };  int main() {     Another<5> a;     a.MyMethod1();     a.MyMethod2(); }  
like image 170
Leandro T. C. Melo Avatar answered Oct 13 '22 06:10

Leandro T. C. Melo