符号'T'未在模板关键字后面的行上解析

symbol 'T' is not resolved on the line after the template keyword

本文关键字:符号 关键字      更新时间:2023-10-16

我对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++ 中不存在。你使用它的方式让我认为它是一个类型名,因为你返回了一个类型为"组件"的元素。您应该首先定义它,或者,如果它应该是因函数的不同调用而异的类型名,则它应该是一个模板参数.
您也不应该在函数的声明中写">",因为它没有意义.
最后但并非最不重要的一点是,函数模板的定义应该在头文件中指定, 因为它是实例化所必需的.
因此,正确的语法应该是:
object.h:

class Object {
public:
template <typename Component, Component T>
const Component &AddComponent() {
// adding component and return statement here.
}
};

示例主.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:对不起,如果我犯了任何英语错误,我是法国人。