Marco A.
Marco A.

Reputation: 43662

Can't explicitly instantiate templated function into templated class

I don't understand why the following code isn't working, why can't I explicitly instantiate the templated function? If I remove that < int > I get a "no matching function call"

#include <iostream>
using namespace std;

template <typename T>
class Xclass
{
public:
  template <typename Y>
  void xfunc()
  {
    cout << "Hello";    
  }
};

template<typename T2>
class Z
{
public:
  void x2()
  {
    Xclass<T2> obj;
    obj.xfunc<int>();
  }
};

int main() {

    Z<int> obj;

    obj.x2();

    return 0;
}

The error is:

prog.cpp: In member function ‘void Z<T2>::x2()’:
prog.cpp:24:15: error: expected primary-expression before ‘int’
     obj.xfunc<int>();
               ^
prog.cpp:24:15: error: expected ‘;’ before ‘int’

Upvotes: 1

Views: 90

Answers (1)

user3286380
user3286380

Reputation: 584

Since the type of obj is a dependent type, you must use the template keyword to tell the compiler it is a template:

Xclass<T2> obj;
obj.template xfunc<int>();

See Where and why do I have to put the "template" and "typename" keywords? for a thorough explanation of when you have to use template.

Upvotes: 3

Related Questions