C++ class with a template and different template member variables
My apologies if the title does not accurately describe what I am trying to do.
I am working on a node/scene tree system that is based on the principle of a Doubly Linked List. My base class, Node
, has the member functions getParent
and getChild
that can return the respective node above and below it. I have also implemented the subclasses GameObject
and Scene
that are Nodes with extra members respective to each subclass.
The idea that I'm trying to implement is that I can instantiate a Scene
object which is a Node<Scene>
, and then set either its child or its parent to some other Node
class, Scene
subclass, or a GameObject
subclass and have access to all of their respective members and functions. This is my implementation at the moment
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();
};
And the classes would hopefully be used like this:
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
Is there a way that I could achieve this functionality with what I currently have?
Templates in C++ are not a replacement for OO. Templates provide compile-time polymorphism; OO run-time. You need the latter, so you'll need a common base class.