What is the best way to add an optional payload to a sorted container?
In my case, I have an AvlTree that obviously needs a Key type to sort it with. For this, I created a templated AvlNode
class with the template KeyType
as well as an AvlTree
class with the same template. Due to some old code I just have a KeyType that implements operators for sorting, but also contains a payload that is independent of the key.
However, I think it would be cleaner, to just offer two template types (i.e. add a PayloadType
). While I could just add this, I would then prevent others from using the tree with just a KeyType.
My first thought was to use
template <typename KeyType>
struct AvlNode
{
KeyType key;
};
template <typename KeyType, typename PayloadType>
struct AvlNodePayload : public AvlNode<KeyType>
{
PayloadType Payload;
};
However, my AvlTree always uses the AvlNode
class and stores a root node of that class. Inheriting from that the same way would mean that I'd have to reimplement almost every method to accomodate for the payload node type. Furthermore, I'd have to hide the old root node and then use a new one, just to ensure the correct class. Therefore, this doesn't seem like a good solution to me.
A different way would be to add a default template to the original AvlNode
struct, such that it always carries a payload, but this would obviously be an overhead in data whenever only a key is needed.
I'm not sure if there is an elegant solution to this (perhaps other than staying with what I have right now: If someone wants to have a payload, they need to implement their own Key class/struct - even then searching and deleting would require me to create this key entirely although I don't need the internal payload part).