Search code examples
c++templatesgeneric-programmingtemplate-argument-deduction

template argument deduction failed when calling base function


The following C++ code produces compilation errors.

The compiler (gcc 5.2.0) complains that at line 15 it cannot find matching function for call to 'Derived::test_func()'; yet if test_func() is moved from Base to Derived, it compiles without error.

class Base {
   public:
   int test_func();
};

class Derived : public Base {
public:
template <typename T>
int test_func(T t); 
};

template <typename T>
int Derived::test_func(T t)  
{
 test_func(); // line 15
 return 0;
}

int Base::test_func()
{
  return 0;
}

If the template function calls other functions in the Base class with different names (not the same name as the template function), as the following code shows, it also compiles fine.

class Base {
   public:
   int test_func_diff_name();
};

class Derived : public Base {
public:
template <typename T>
int test_func(T t); 
};

template <typename T>
int Derived::test_func(T t)  
{
 test_func_diff_name();
 return 0;
}

int Base::test_func_diff_name()
{
  return 0;
}

Why is this? What is the constraints specified in C++ in calling base functions from templates? Can someone point me to some resources?


Solution

  • In C++, functions in derived classes which don't override functions in base classes but which have the same name hide all other functions with the same name in the base class.

    It is usually preferable to give different functions different names.

    If you really need it, you can call the base class' function by fully qualifying the name, like Base::test_func();

    Or explicitly introduce the base class' names into the current class with using Base::test_func;