Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why base function cannot be accessed by derived class when involving template classes

Tags:

c++

templates

The following code is giving 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();
}

ERROR

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 coming?

like image 475
cppcoder Avatar asked Apr 25 '12 08:04

cppcoder


1 Answers

The name foo() does not depend on any of Derived's template parameters - it's a non-dependent name. The base class where foo() is found, on the other hand - Base<T> - does depend on one of Derived's template parameters (namely, T), so it's a dependent base class. C++ does not look in dependent base classes when looking up non-dependent names.

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

This C++ FAQ item explains it nicely: see http://www.parashift.com/c++-faq-lite/templates.html#faq-35.19

like image 66
HighCommander4 Avatar answered Sep 22 '22 23:09

HighCommander4