Why explicitly declare the base when calling function when using templates?

Asked

Viewed 185 times

3

I have the following code: A derivative template calling a base function also template.

template <int M>
struct Base { void foo() {} };

template <int M>
struct Derived : public Base<M> {
    void bar() { foo(); }
};

But this causes the following mistake:

main.cpp: In Member Function void Derived<M>::bar():
main.cpp:7:22: error: there are no Arguments to foo that Depend on a template Parameter, so a declaration of foo must be available [-fpermissive]

void bar() { foo(); }

Error correction is simple, just use Base<M>::foo(); in place of the foo().

My question is: Why this error occurs? Why was this restriction imposed that I must clarify the basis manually and that the compiler cannot deduce this on its own? Why only when using templates? My code is somehow ambiguous?

1 answer

6


This is because the compiler does not search for symbols in template parameter-dependent base classes in name resolution C++FAQ.

To do this the compiler would need to wait until the template is instantiated to resolve the names, and once for each instance of it, which would slow the compilation process (even) down.

As specified, the compiler looks for foo while bar is still a template, and as it is not explicitly qualified it does not look in the base class. Even if in the general case it has the foo, you could create a specialization of it without this method.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.