Why a basic function cannot be obtained by a derived class when using template classes

The following code gives a compilation error:

template <typename T> class Base { public: void bar(){}; }; template <typename T> class Derived : public Base<T> { public: void foo() { bar(); } //Error }; int main() { Derived *b = new Derived; b->foo(); } 

MISTAKE

Line 12: error: there are no arguments to 'bar' that depend on a template parameter, so a declaration of 'bar' must be available

Why is this error occurring?

+8
c ++ templates
source share
2 answers

The name foo() does not depend on any parameters of the Derived template - this is an optional name. The base class, where foo() found, on the other hand, Base<T> , depends on one of the parameters of the Derived template (namely, T ), therefore it is a dependent base class. C ++ does not look into dependent base classes when looking for non-dependent names.

To solve this problem, you need to qualify the bar() call in Derived::foo() as this->bar() or Base<T>::bar() .

This question in C ++ often explains it beautifully: see http://www.parashift.com/c++-faq-lite/templates.html#faq-35.19

+14
source share

The code you provided does not have a build error in the line you specify. Here it is:

 Derived *b = new Derived; 

which should read:

 Derived<int> *b = new Derived<int>(); 

(or use whatever type you want instead of int.)

0
source share

All Articles