0

Code:

#include <iostream>

struct S {
    template<typename T>
    void method() const;
};

template<typename T>
void S::method() const {
    std::cout << "Hello World\n";
}

template<typename Obj>
void func(const Obj& obj) {
    obj.method<int>();
}

int main() {
    S s;
    func(s);
}

When I try to compile this code I get the following error:

<source>:15:16: error: expected primary-expression before 'int'
   15 |     obj.method<int>();
      |                ^~~
<source>:15:16: error: expected ';' before 'int'
   15 |     obj.method<int>();
      |                ^~~
      |                ;

Is there any way to call this function, if you have to explicitly specify the template argument?

  • 5
    Does this answer your question? [Where and why do I have to put the "template" and "typename" keywords?](https://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords) – Const Aug 17 '21 at 07:18

1 Answers1

2

You have to add template:

template<typename Obj>
void func(const Obj& obj) {
    obj.template method<int>();
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302