2

I'm struggling with a compilation issue. Given a Base class templated with T that contains a method templated with U, I can't call the method from a derived class. The following example reproduces my problem:

#include <iostream>
#include <vector>

template <class T>
class Base
{
protected:
  template <class U>
  std::vector<U> baseMethod() const
  {
    return std::vector<U>(42);
  }
};

template <class T>
class Derived : public Base<T>
{
public:
  std::vector<int> derivedMethod() const
  {
    return baseMethod<int>();
  }
};

int main ()
{
  Derived<double> d;
  std::vector<int> res = d.derivedMethod();
  return 0;
}

Compiler result:

t.cc:21:12: error: ‘baseMethod’ was not declared in this scope
t.cc:21:23: error: expected primary-expression before ‘int’
t.cc:21:23: error: expected ‘;’ before ‘int’
t.cc:21:26: error: expected unqualified-id before ‘>’ token
crep4ever
  • 93
  • 1
  • 5

1 Answers1

2

You should add the template keyword to treat baseMethod as a dependent template name:

std::vector<int> derivedMethod() const
{
  return this->template baseMethod<int>();
}

In a template definition, a dependent name that is not a member of the current instantiation is not considered to be a template name unless the disambiguation keyword template is used (or unless it was already established as a template name).

For further details: Where and why do I have to put the "template" and "typename" keywords?

Community
  • 1
  • 1
manlio
  • 18,345
  • 14
  • 76
  • 126