c++boosttypesdictionaryboost-extension

Boost how to create a map for types selection?


so i use BOOST.EXTENTION to load modules. I have a special file that describes each module. I read variables from that file.

so such example:

shared_library m("my_module_name");
// Call a function that returns an int and takes a float parameter.
int result = m.get<int, float>("function_name")(5.0f);
m.close();

for me would turn into:

shared_library m("my_module_name");
// Call a function that returns an int and takes a float parameter.
int result = m.get<myMap["TYPE_1_IN_STRING_FORM"], myMap["TYPE_2_IN_STRING_FORM"]>("function_name")(5.0f);
m.close();

How to create such map that would map standard and costume types?

Update:

may be with variant:

  shared_library m("my_module_name");
  int result = m.get<boost::variant< int, float, ... other types we want to support >, boost::variant< int, float, ... other types we want to support > >("function_name")(5.0f);
    m.close();

can halp? so we would not care as long as all types we want are declared in it?


Solution

  • For that, you would need a heterogeneous map - that is, its elements can be of different types. Furthermore you would need the ability to return types from functions, not just variables.


    Now, a heterogeneous map would be possible with Boost.Variant or a simple union, but that binds it to compile time: we need to know every type that is possible to create that variant/union.
    Of course a Boost.Any would be possible to store everything and its dog, but the problem strikes again: you need to extract the real type out of that Boost.Any again. The problem repeats itself. And if you know the real type, you can aswell just make a variant/union and save yourself the any_cast trouble.


    Now, for another troublesome thing:

    m.get<myMap["TYPE_1_IN_STRING_FORM"], myMap["TYPE_2_IN_STRING_FORM"]>
    

    To make the above line work, you'd need two features that C++ doesn't have: the ability to return types and runtime templates. Lets ignore the first point for a moment.
    Templates are compile-time, and the get function is such a template. Now, to use that template, your myMap would need to be able to return types at compile-time, while getting populated at runtime. See the contradiction? That's why runtime templates would be needed.


    Sadly, exactly those three things are not possible (or extremely hard and very very limited) in C++ at runtime: heterogeneous data types (without constant size), returning types and templates.
    Everything that involves types needs to be done at compile-time. This blogpost by @Gman somewhat correlates with that problem. It's definitly worth a read if you want to know what C++ just can't do.


    So, to conclude: You'll need to rethink and refactor your problem and solution. :|