There are two options that I can think of. One of them is to use polymorphism, in which you have an abstract base class, Node and a number of subclasses of the type. Perhaps something like:
class Node { public: virtual ~Node() = 0; }; class String : public Node { public: ~String() {} }; class Float : public Node { public: ~Float() {} };
When storing these nodes, you will save Node* , not void* . The presence of an (abstract) virtual destructor in the base class allows you to correctly destroy specific objects using the base class pointer, for example:
Node* obj = new String; delete obj;
You can also call methods declared in the base class and execute their code in the correct derived class if these methods are virtual in the base class. they will often also be pure virtual, for example:
class Node { public: std::string Speak() const = 0;
Another option is to use some kind of variant class. C ++ itself does not have an alternative class built into the language, but some libraries have been written, such as Boost, that provide such a class.
source share