I have a series of several similar structures, e.g.,
map<key1, attr1>; map<key2, attr2>; ...,
meanwhile, in correspondence, a series of array,
// JUST TO SHOW THE IDEA, NOT SYNTAX CORRECT
class {key_1; attr_1;} array [#]; class {key_2; attr_2;} array [#]; ...,
and keyX and key_X share the similar structure, as well as attr, e.g.
struct key1 {int k1;}; class key_1 {int k_1;};
struct key2 {int k1; int k2;}; class key_2 {int k_1; int k_2;};
...
struct attr1 {int a1; int a2;}; class attr_1 {int a_1; int a_2;};
I need to write a function, like overloading the assignment operator, to convert the data from map_series to the other, and vice versa.
So instead of doing it map by map, key by key, and int by int, is there some template-wise way to do it, so the code would be generic,or save more lines of code? What could be the smart way to do this?
EDIT 1:
Unfortunately, one constraint due to our legacy system, the type convertion between struct, e.g. key1, key_1, does not work as C++ primitives, so a conversion function also have to be provided.
EDIT 2:
inspired by J.N. answer, is it possible to have something like:
template <class KeyMap, class ValueMap, class KeyArr, class ValueArr> void convert (map<KeyMap, ValueMap>, class {KeyArr, ValueArr} array[]){};
how to generlize the conversion for key and attr? like
template <class KeyMap, class KeyArr> void convert_key(KeyMap, KeyArr){}
Ok so let’s suppose we have this:
Let’s define the conversion function first:
Then, in C++, you can’t return arrays. Actually you usually don’t work with array, people usually prefer
std::vector. (If you really need an array then you need to allocate it and return a pointer to it or wrap it in a smart pointer)Then it is enough to browse the values in the map and push them into the vector:
note: if you do not have a C++11 compiler, use:
That will do the job for ONE map and one type. Now we can generalize the conversion function by using templates:
And use it like this:
You could go further by creating a list of types to convert using
boost::mplbut that should be in another question.EDIT: generalize the conversion of the types
As you mentioned, there’s no generic way to convert the types, we’ll have to write all the conversion functions. So the only thing we can do is make it more elegant by implementing implicit conversion operators like this:
This simplifies our conversion function (updated to take into account the array)
EDIT 2: We can use
std::pairto generalize the array structure: