我不确定是否可以做到这一点,我只是深入研究模板,所以可能我的理解有一点错误。
我有一个排的士兵,这个排继承了一个编队来获取编队属性,但是因为我可以有尽可能多的编队,所以我选择使用CRTP来创建编队,希望我可以创建一个排的矢量或数组来存储排。但是,当然,当我创建一个Platoon时,它不会将其存储在向量中,“类型是无关的”
有什么办法可以解决这个问题吗?我读到过类似的“贴面”,它们使用数组工作,但我不能让它工作,也许我遗漏了一些东西。
这里有一些代码:(很抱歉我的格式,代码在我的帖子里,但由于某些原因没有出现)
template < class TBase >
class IFormation
{
public :
~IFormation(){}
bool IsFull()
{
return m_uiMaxMembers == m_uiCurrentMemCount;
}
protected:
unsigned int m_uiCurrentMemCount;
unsigned int m_uiMaxMembers;
IFormation( unsigned int _uiMaxMembers ): m_uiMaxMembers( _uiMaxMembers ), m_uiCurrentMemCount( 0 ){} // only allow use as a base class.
void SetupFormation( std::vector<MySoldier*>& _soldierList ){}; // must be implemented in derived class
};
/////////////////////////////////////////////////////////////////////////////////
// PHALANX FORMATION
class Phalanx : public IFormation<Phalanx>
{
public:
Phalanx( ):
IFormation( 12 ),
m_fDistance( 4.0f )
{}
~Phalanx(){}
protected:
float m_fDistance; // the distance between soldiers
void SetupFormation( std::vector<MySoldier*>& _soldierList );
};
///////////////////////////////////////////////////////////////////////////////////
// COLUMN FORMATINO
class Column : public IFormation< Column >
{
public :
Column( int _numOfMembers ):
IFormation( _numOfMembers )
{}
~Column();
protected:
void SetupFormation( std::vector<MySoldier*>& _soldierList );
};然后,我在platoon类中使用这些结构来派生,以便platoon获得相关的SetupFormation()函数:
template < class Formation >
class Platoon : public Formation
{
public:
**** platoon code here
};到目前为止,一切都运行得很好,正如预期的那样。
现在,因为我的将军可以有多个排,所以我需要存储这些排。
typedef Platoon< IFormation<> > TPlatoon; // FAIL
typedef std::vector<TPlatoon*> TPlatoons;
TPlatoon m_pPlatoons
m_pPlatoons.push_back( new Platoon<Phalanx> ); // FAIL, types unrelated.TPlatoon;失败,因为我需要指定一个模板参数,但是指定它只允许我存储使用相同模板参数创建的排。
所以我创建了FormationBase
class FormationBase
{
public:
virtual bool IsFull() = 0;
virtual void SetupFormation( std::vector<MySoldier*>& _soldierList ) = 0;
};并使IFormation公开继承,然后将类型定义函数更改为
typedef Platoon< IFormation< FormationBase > > TPlatoon;但还是没有爱。
现在,在我的搜索中,我没有找到说明这是可能的或不可能的信息。
发布于 2010-06-15 10:46:40
C++不允许简单地使用编译时和运行时多态性。您的向量只能包含一种类型,这一点是正确的。你必须让你的向量存储一个指向非模板类型的指针,或者改变设计不使用向量。
如果您想让CRTP的类公开继承自FormationBase,那么向量必须是一个std::vector<FormationBase *>。从运行时类FormationBase返回到实例化它的编译时模板参数是不可能的。
考虑到您的数据看起来相对一致,并且您只想更改算法在战场上排列士兵和单位的方式,我会考虑使用策略模式来指定SetupFormation函数,并使用存储在向量中的类创建一个独立的、非多态的类。
https://stackoverflow.com/questions/3042191
复制相似问题