c++ - 在模板关键字之后的行上未解析符号“T”
问题描述
我对 C++ 很陌生,但知道大多数其他主流编程语言。我在网上寻找解决我问题的方法,但似乎找不到。到目前为止,这是我的一些代码:
对象.h:
class Object final {
public:
template <Component T>
const Component& AddComponent<T>();
};
对象.cpp:
#include "object.h"
template <Component T>
const Component& Object::AddComponent<T>() {
}
问题是在模板关键字之后的行上没有解析符号“T”。我在 linux 上使用 eclipse 和 g++ 编译器。
解决方案
首先,在 c++ 中,final 关键字意味着子类不能重载虚拟类方法,这不是您使用它的方式。因此,该关键字应该消失。
然后,“组件”在 C++ 中不存在。你使用它的方式让我觉得它是一个类型名,因为你正在返回一个“组件”类型的元素。您应该首先定义它,或者,如果它应该是一个随函数的不同调用而变化的类型名,它应该是一个模板参数。
你也不应该在函数的声明中写“<T>”,因为它没有意义。
最后但同样重要的是,函数模板的定义应该在头文件中指定,因为它是实例化所必需的。
class Object {
public:
template <typename Component, Component T>
const Component &AddComponent() {
// adding component and return statement here.
}
};
例如 main.cpp:
#include "object.h"
int main() {
Object obj;
obj.AddComponent<int, 4>();
return 0;
}
object.h(如果“组件”是预定义的):
class Object {
public:
template <Component T>
const Component &AddComponent() {
// adding component and return statement here.
}
};
main.cpp(如果“组件”是预定义的):
#include "object.h"
int main() {
Object obj;
obj.AddComponent<4>();
return 0;
}
祝你今天过得愉快。
PS:对不起,如果我犯了任何英语错误,我是法国人。
推荐阅读
- json - Flutter json 1处的意外字符
- java - 在 Spring Boot 应用程序中使用 JAX-RS 的 Swagger UI (SpringFox) - 无法加载 API 定义
- javascript - webstomp JS - 尝试发送rabbitmq消息时拒绝非环回访问
- java - findAllByEntityFieldName() 有时会使用 JPA 存储库返回不正确的数据
- python - 如何将 [array([[]])] 转换为一维数组?
- reactjs - 使用 Slim 插件 MERN 时出现 CORS 问题
- ruby-on-rails - 在执行 Marshal.load 时继续不被委派
- c# - 我的电脑中的“使用系统”在哪里
- android - 错误:OnBackPressed(); 没有按预期工作
- python-3.x - 如何在没有任何其他字符的情况下转换此日期时间格式?