2013-01-25 115 views
-1
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 
    } 
}; 

但调用相同的方法从另一个地方工作!像main()。 这段代码有什么问题!!!C++从类本身的非模板类调用模板方法

+3

也许试着改变'Transform'函数的名字,使它和'Transform'类的名字不一样? –

+0

那么,明显'转换'从来没有被定义... –

+0

这只是代码的一部分。请!..... – Penman

回答

1

您提供的代码有错别字,因为已经提到。修复它们后,你会得到你提到的错误。

你得到它的原因是,你有一个名字为Transform的成员函数,与你想要为其设置GetComponent的类型相同。因此,解决方案是使用完整类型名称(包括名称空间)“帮助”编译器。这假定Transform在全局命名空间中定义:

Transform* Transform() { 
    return this->GetComponent<::Transform>(); 
} 

使用这个,如果你已经在一个命名空间中定义它:

Transform* Transform() { 
    return this->GetComponent<::YOUR_NAMESPACE::Transform>(); 
} 

编辑:完整的代码我使用:

class Node; 
class Transform 
{ 
public: 
    Transform(Node*); 
}; 

class Node { 
public: 
    template <class T> 
    T* GetComponent() { 
     return new T(this); 
    } 

    Transform* Transform() { 
     return this->GetComponent<::Transform>(); 
    } 
};