1

Consider the following code:

#include <iostream>

class X
{
protected:
  void func()
  {
    std::cout << 0 << std::endl;
  }
};

class A : public X
{
public:
  void test()
  {
    func();
  }
};

Everything works exactly as expected - when calling A::test, the code calls X::func(). However, if I add a template parameters to the mix, it appears that I have confused the compiler. See below:

#include <iostream>

template <typename T>
class X
{
protected:
  void func()
  {
    std::cout << 0 << std::endl;
  }
};

template <typename T>
class A : public X<T>
{
public:
  void test()
  {
    func();
  }
};

Now, the compilation gives me the error:

test.cpp: In member function ‘void A<T>::test()’:
test.cpp:19:12: error: there are no arguments to ‘func’ that depend on a template parameter, so a declaration of ‘func’ must be available [-fpermissive]
       func();
            ^
test.cpp:19:12: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)

This can be easily rectified by using this->func() in place of func() (which compiles and works as expected), but the question is: Why is it that when I use a template parameter, I need to explicitly tell the compiler where to look up the method (i.e., within this), but when I don't, I do not?

Note: This was tested with GCC 4.8.5.

user11923373
  • 471
  • 2
  • 11
  • 1
    TL;DR of the dupe: `func` is now a non-dependent name in the template. Those aren't looked up unless you do the call through `this` – NathanOliver Nov 14 '19 at 21:38
  • @NathanOliver-ReinstateMonica: Makes sense, thanks - also for the link to the dupe. Somehow did not find that in my search. – user11923373 Nov 14 '19 at 21:41

0 Answers0