简体   繁体   中英

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

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?

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

The code you've provided doesn't have a build error on the line you indicate. It DOES have one here:

Derived *b = new Derived;

which should read:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM