I have this problem again and again… and still have not a satisfactory answer…
Especially when I put the class into a container, later on I need to record more information on every element in the container during a specific processing, but after processing I do not need the extra information anymore….
I often found some libraries try to solve the above situation by defining a void* in their data structure to provide user-defined data structure extension. Just the same described in this Q&A.
But it produces memory / resource handling problem… and other problems that I feel this approach is error-prone.
In the modern day of object-oriented programming, I am thinking of
using inheritance & polymorphism. Use base class’s pointer in the container, but then I have to add derived class’s accessor into the base class. It is kind of strange…
is there any other better ways to extend a class’s property while maintain container comparability in C++?
The best way to store extra data about a object without actually compromising the integrity of the object itself is to store a pair of data in the container instead.
Now I can create a container type in C++ which stores both pieces of information together without compromising the independence of either type.