首页 > 解决方案 > 如何调用模板参数的模板方法?

问题描述

代码:

#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);
}

当我尝试编译此代码时,出现以下错误:

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

如果必须显式指定模板参数,有什么方法可以调用此函数?

标签: c++templates

解决方案


您必须添加template

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

推荐阅读