我不知道为什么std::is_base_of
在这里不起作用。我将子类“ Player”(父类:Character)和“武器”(父类:GameObject)传递为World :: spawn()函数的参数,如下所示,但是std::is_base_of<Parent,Child>::value
无法推断出它们的关系。我希望第一个if语句仅传递具有字段name
的Character对象,而武器对象应传递给第二个if语句。
我收到错误(GNU编译器):
World.cpp:以‘void World :: spawn(OBJ &&,int, int)[with OBJ = Player&; T = int; unsigned int SZ = 10u]’: World.cpp:98:58:从这里需要World.cpp:74:37:错误: '类 玩家”没有名为“ getID”的成员std :: cout <<“生成对象 \“” << obj.getID()<<“ \” at(“ <<< x <<”,“ << y <<”)\ n“;
^ World.cpp:76:42:错误:“类播放器”没有名为“ getID”的成员。
if(m_WorldMap.set(std :: stoi(obj.getID()),x,y))
代码是:
template<typename T, std::size_t SZ>
template<typename GTYPE>
void World<T,SZ>::spawn(GTYPE&& gameType, int x, int y)
{
if(std::is_base_of<Character, GTYPE>::value)
{
std::cout << "Spawning character \"" << obj.getName() << "\" at (" << x << ", " << y << ")\n";
if(m_WorldMap.set(obj.getHP(), x, y))
std::cout << "Successfully spawned \"" << obj.getName() << "\" at (" << x << ", " << y << ")\n";
else
throw SpawnException();
}
else if(std::is_base_of<GameObject, GTYPE>::value)
{
std::cout << "Spawning object \"" << obj.getID() << "\" at (" << x << ", " << y << ")\n";
if(m_WorldMap.set(std::stoi(obj.getID()), x, y ))
std::cout << "Successfully Spawned Object.\n";
else
throw SpawnException();
}
else
throw SpawnException();
}
int main()
{
World<int, 10> GameWorld;
Player boxHead(200, 3, 5, "Box Head");
GameWorld.spawn(boxHead, boxHead.getX(), boxHead.getY());
GameWorld.showMap();
}