Using C ++, I am trying to create a generic container class to handle several data types. This is a common problem with many solutions, but I did not find anything as ... intuitive as I'm used to in languages ββlike Python or even VB / VBA ...
So here is my scenario:
I built the DataContainer class based on boost :: any, which I use to store multiple data types from multiple elements. I am using a map declared as:
std::map<std::string, DataContainer* (or DataContainerBase*)>
where DataContainer is a class that encapsulates an object of type:
std::list<boost::any>
along with convenient functions for managing / accessing the list.
However, in the end, I am still forced to do type conversions outside the data container.
For example, if I were to store a list of int values ββon a map, accessing them would require:
int value = boost::any_cast<int>(map["myValue"]->get());
I would prefer the boost code to be contained completely inside the data container structure, so I only need a type:
int value = map["myValue"]->get();
or, in the worst case:
int value = map["myValue"]->get<int>();
Of course, I could list my data types and do something like:
int value = map["myValue"]->get( TYPE_INT );
or write type-specific get () functions:
getInt(), getString(), getBool() ...
The problem with the last two parameters is that they are somewhat inflexible, so I must explicitly specify each type that I want to store in the container. The any_cast solution (which I implemented and works), I suppose, is fine, is it just ... inelegant? I do not know. It seems I also do not need to use external mechanics outside.
As I see it, passing a value without declaring a value type in a call to the DataContainer member function will require a void * solution (which is undesirable for obvious reasons), and using the get () call will require (as far as I can tell) the member function of the "virtual template" defined at the base class level, which, of course, is not allowed.
Be that as it may, I have a workable solution, and indeed, my use in this case is quite limited in scope, that most of any solutions will work well. But I'm wondering if there could be a more flexible way to manage a universal, multi-type data container than this.