【发布时间】:2022-01-11 08:00:23
【问题描述】:
如果标题没有准确描述我想要做的事情,我深表歉意。
我正在研究基于双链表原理的节点/场景树系统。我的基类Node 具有成员函数getParent 和getChild,它们可以返回其上方和下方的相应节点。我还实现了子类GameObject 和Scene,它们是节点,每个子类都有额外的成员。
我试图实现的想法是我可以实例化一个Scene 对象,它是一个Node<Scene>,然后将其子类或父类设置为其他Node 类、Scene 子类,或GameObject 子类,并且可以访问它们各自的所有成员和函数。这是我目前的实现
template<class classType>
class Node
{
private:
std::string name;
//Hypothetical thing I want to do. Parent or child can be a Node of any type
template<class T>
Node<T>* parent;
template<class T>
Node<T>* child;
public:
Node() {
// Constructor things...
};
// Return the correct class type for the child or parent
Node* getChildNode() { return child; };
Node* getParentNode() { return parent; };
// Setter functions can accept a node of any type
template<class T>
void setChildNode(Node<T> *new_child){
child = new_child;
};
template<class T>
void setParentNode(Node<T> *new_parent){
parent = new_parent;
};
}
class Scene : public Node<Scene>
{
public:
Scene();
void foo();
};
class GameObject : public Node<GameObject>
{
public:
GameObject();
void bar();
};
希望这些类可以这样使用:
Scene* root = new Scene();
GameObject* platform = new GameObject();
platform->setParentNode(root); //"error: cannot convert ‘Node<Scene>*’ to ‘Node<GameObject>*’ in assignment"
platform->getParentNode().foo(); //Call function specific to a Scene class
有没有一种方法可以用我目前拥有的东西来实现这个功能?
【问题讨论】:
-
使用自定义类型列表(如
std::tuple<Scene, GameObject>),您可能能够拥有下一个类型(在编译时已知)。不确定这是你想要的。
标签: c++ list templates game-development doubly-linked-list