I have an application where a specific message type needs to be selected based on user input (a string or int). There is a 1:1 mapping of a (string or int to a fixed type). For example 1-> int or "Apple"-> struct Apple ..and so on.
I tried to map int to a type using a template GetType<>.
struct messageA {int x;};
struct messageB {double y;};
/// Trying to map int to a type
template<int>
struct GetType{};
template<>
struct GetType<1> {
using type = messageA;
};
template<>
struct GetType<2> {
using type = messageB;
};
///
/// this some_task function is called from some UI
void some_task(int ID) {
// here I can not use the ID value in GetType< >
typename GetType<1>::type *msg = new typename GetType<1>::type();
some_other_generic_function(msg);
}
But it seems I can not use this, inside the function some_task because ID is a runtime argument.
The switch case is an option but then every time when a new message type is needed, I need to change the switch case.
What other ways can we achieve the association from int to type? Can we create some sort of list of types and which can be indexed with int (actually I needed string, but I will deal with strings later)?
std::map?std::variant<messageA, messageB>seems to be what are after. Should play well with a visitor that invokessome_other_generic_function.