C++ C++;从类本身调用非模板类中的模板方法 类节点{ 公众: 模板T*GetComponent(){ 返回新的T(this);//实际代码更复杂! } Transform*Transform(){ 返回此->GetComponent();//对于“T”的模板参数无效,应键入 } };

C++ C++;从类本身调用非模板类中的模板方法 类节点{ 公众: 模板T*GetComponent(){ 返回新的T(this);//实际代码更复杂! } Transform*Transform(){ 返回此->GetComponent();//对于“T”的模板参数无效,应键入 } };,c++,templates,C++,Templates,但是从另一个地方调用相同的方法是有效的!比如main()。 这个代码有什么问题 如前所述,您提供的代码有拼写错误。在修复它们之后,您将得到您提到的错误 得到它的原因是,您有一个名为Transform的成员函数,该函数与要具体化的GetComponent类型相同。因此,解决方案是通过使用完整的类型名(包括名称空间)来“帮助”编译器。这假设在全局命名空间中定义了Transform: class Node { public: template<class T> T* GetCom

但是从另一个地方调用相同的方法是有效的!比如main()。
这个代码有什么问题

如前所述,您提供的代码有拼写错误。在修复它们之后,您将得到您提到的错误

得到它的原因是,您有一个名为
Transform
的成员函数,该函数与要具体化的
GetComponent
类型相同。因此,解决方案是通过使用完整的类型名(包括名称空间)来“帮助”编译器。这假设在全局命名空间中定义了
Transform

class Node {
public:
  template<class T>  T*   GetComponent() {
     return new T(this);  // actual code is more complicated!
  }

  Transform*   Transform() {
      return this->GetComponent<Transform>();   // invalid template argument for 'T', type expected
  }
};
Transform*   Transform() {
    return this->GetComponent<::Transform>();
}
Transform*Transform(){
返回此->GetComponent();
}
如果已在命名空间中定义它,请使用此选项:

class Node {
public:
  template<class T>  T*   GetComponent() {
     return new T(this);  // actual code is more complicated!
  }

  Transform*   Transform() {
      return this->GetComponent<Transform>();   // invalid template argument for 'T', type expected
  }
};
Transform*   Transform() {
    return this->GetComponent<::Transform>();
}
Transform*Transform(){
返回此->GetComponent();
}
编辑:我使用的完整代码:

Transform*   Transform() {
    return this->GetComponent<::YOUR_NAMESPACE::Transform>();
}
类节点;
类转换
{
公众:
变换(节点*);
};
类节点{
公众:
模板
T*GetComponent(){
返回新的T(本);
}
Transform*Transform(){
返回此->GetComponent();
}
};

可能尝试更改
Transform
函数的名称,使其与
Transform
类的名称不同?显然,
Transform
从未定义过……这只是代码的一部分。请…..
Transform
应该是什么。一个函数还是一个类型?@AndyProwl:谢谢