首页 > 解决方案 > 在模板关键字之后的行上未解析符号“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++

解决方案


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


推荐阅读