Dispatching from a runtime parameter to different overloads

Suppose I have a set of types :

constexpr std::tuple<int,double,string> my_types;

a set of values to identify them:

constexpr std::array<const char*,3> my_ids = {"int","double","string"}; // const char* instead of string to be constexpr-compatible

and an overload set

template<class T> bool my_fun(my_type complex_object) { /* some treatment depending on type T */ }

I have a manually dispatching function like that:

string my_disp_fun(my_type complex_object) {
  const char* id = get_info(complex_object);
  if (id == "int") {
    return my_fun<int>(complex_object);
  } else if (id == "double") {
    return my_fun<double>(complex_object);
  } else if (id == "string") {
    return my_fun<string>(complex_object);
  } else {
    throw;
  }
}

I would like to replace it by something like that:

struct my_mapping {
  static constexpr std::tuple<int,double,string> my_types;
  static constexpr std::array<const char*,3> my_ids = {"int","double","string"}; // const char* instead of string to be constexpr-compatible
}

string my_disp_fun(my_type complex_object) {
  const char* id = get_info(complex_object);
  return
    dispatch<my_mapping>(
      id, 
      my_fun // pseudo-code since my_fun is a template
    );
}

How to implement the dispatch function? I am pretty confident it can be done but so far, I can’t think of a reasonably nice API that would still be implementable with template metaprograming tricks.

I am sure people already had the need for this kind of problem. Is there a name for this pattern? I don’t really know how to even qualify it in succinct technical terms…

Side question: is it related to the pattern matching proposal? I’m not sure because the paper seems more interested in the matching part, not generating branchs from that, right ?

Source: Windows Questions C++

LEAVE A COMMENT