c++ - 如何调用模板参数的模板方法?
问题描述
代码:
#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>();
| ^~~
| ;
如果必须显式指定模板参数,有什么方法可以调用此函数?
解决方案
您必须添加template
:
template<typename Obj>
void func(const Obj& obj) {
obj.template method<int>();
}
推荐阅读
- java - servlet.service 错误,classNotFoundException
- r - 如何修复R中非数字矩阵中的错误
- swiftui - 警报视图 - 在切换结果中
- c - 数据类型范围的真正含义是什么?
- javascript - 如何在reactjs中检查以带有Route hook的短语开头的随机生成的url
- apache-spark - 在 PySpark 中的 JOIN 内创建列并用作连接键
- laravel - 删除现有的 Where 子句
- html - 强制更改整个背景颜色,忽略 div(HTML、CSS)
- mulesoft - 如何使用 Exchange API 发布自定义策略?
- python - 有没有用`python-attrs`记录属性的好方法?