Given some definitions
#include <iostream> #include <iterator> #include <algorithm> #include <stdexcept> #include <map> using namespace std; struct state{ int debug_level = 1; const char* debug_out = "%s"; } s; // some functions to call void SLL(state& s, int, int, int, int){ cout << "SLL"; } void SLR(state& s, int, int, int, int){ cout << "SLR"; } void SLT(state& s, int, int, int, int){ cout << "SLT"; }
You can use the card
auto mappedname2fn = map<string, delctype(SLL)*>{ {"SLL", SLL}, {"SLR", SLR} }; // call a map function mappedname2fn["SLR"](s, 1, 2, 3, 4);
If you don't need a map, you can use a pre-sorted array for binary search
Here's a binary search for an array of names, pairs of functions
template<typename P, int N, typename ...T> auto callFn(P(&a)[N], string val, T&&... params){ auto it = lower_bound(a, a+N, make_pair(val, nullptr), [](auto& p1, auto& p2){return p1.first < p2.first;}); if(it==(a+N) || val<it->first) throw logic_error("not found"); return it->second(forward<T>(params)...); }
So you can configure the array and use it: -
// array sorted in alphabetical order for binary search to work pair<string, decltype(SLL)*> name2fn[] = { {"SLL", SLL}, {"SLR", SLR}, {"SLT", SLT} }; void callFn(string name, state& s, int a, int b, int c, int d){ try{ callFn(name2fn, name, s, a, b, c, d); } catch(exception& e){ cout << e.what(); } } // call it callFn("SLL", s, 1, 2, 3, 4);