我有以下代码:
class VPersistence {
public:
static VPersistence& get_instance() { return instance; }
// prohibit copy & move
VPersistence(const VPersistence&) = delete;
VPersistence(VPersistence&&) = delete;
VPersistence& operator=(const VPersistence&) = delete;
VPersistence& operator=(VPersistence&&) = delete;
void SetClass(Character* t);
Character* GetClass();
private:
static VPersistence instance;
VPersistence() {}
Character* _character;
};
我希望能够存储Warrior / Mage /等。它们来自Character。但是当调用GetClass()时,我希望它返回具体类型而不指定要返回的类型,因为我已经在SetClass()中指定了它。我有什么选择?我该如何解决这个问题?
对于上下文:我有一个主菜单,我想在其中设置可玩类,其他场景/关卡需要调用该类来了解哪个具体角色正在玩游戏。
所以我之前的是:
VPersistence<Warrior> vpersistence;
auto warrior = new Warrior(start_x, start_y, width, height);
warrior->AddComponent(new Game::CameraComponent(800, 600));
vpersistence.SetClass(warrior);
Objects.AddObject(vpersistence.GetClass());
我以前的VPersistence类看起来像这样:
template <class T>
class VPersistence {
public:
void SetClass(T* t);
T* GetClass();
private:
T* _character;
};
template<class T>
inline void VPersistence<T>::SetClass(T* t)
{
static_assert(std::is_base_of<Character, T>::value, "T must derive from
Character.");
this->_character = t;
}
template<class T>
inline T* VPersistence<T>::GetClass()
{
return this->_character;
}