【问题标题】:C++ class with a template and different template member variables具有模板和不同模板成员变量的 C++ 类
【发布时间】:2022-01-11 08:00:23
【问题描述】:

如果标题没有准确描述我想要做的事情,我深表歉意。

我正在研究基于双链表原理的节点/场景树系统。我的基类Node 具有成员函数getParentgetChild,它们可以返回其上方和下方的相应节点。我还实现了子类GameObjectScene,它们是节点,每个子类都有额外的成员。

我试图实现的想法是我可以实例化一个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&lt;Scene, GameObject&gt;),您可能能够拥有下一个类型(在编译时已知)。不确定这是你想要的。

标签: c++ list templates game-development doubly-linked-list


【解决方案1】:

C++ 中的模板不能替代 OO。模板提供编译时多态性; OO 运行时。你需要后者,所以你需要一个通用的基类。

【讨论】:

  • 我已经在使用Node 作为公共基类,然后有SceneGameObject 的子类,但我不明白我怎么会有GameObject 返回一个可能是Scene 或另一个GameObject 的父级?我是否可以将parentchild 类型的成员设为auto
  • @Gman0064:Node 目前不是类,Node 是类模板。 Scene 并非源自Node,而是源自Node&lt;Scene&gt;。技术上允许,但很奇怪。另外,我也不知道为什么要将场景和游戏对象混合在一个列表中。但既然你这样做了,任何一方的父母都可以是。 auto 不是一个神奇的修复方法。这又是编译时多态性。
猜你喜欢
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 2013-05-11
相关资源
最近更新 更多