I have a class with (private) functions and different arguments. I want to put these into a map and then call them with a single function that accepts variadic arguments. I am fine to have a bad_any_cast
on mismatching invocations (like using v.call("Bob", 1)
in the example below). This post solution is pretty close to what I want to accomplish but I cannot get it working with member functions, std::function or lambda (any of that would be fine).
Here is my minimal example I am trying to get running. My issues are the initialization of calls map and calling some any from the map. I can use anything up to C++17.
#include <any>
#include <iostream>
#include <map>
using namespace std;
class VarCall {
public:
VarCall() : calls({{"Alice", foo}, {"Bob", bar}, {"Charlie", baz}}) {}
template <typename... Args>
void call(const string& what, Args... args) {
any_cast<???>(calls[what])(args...);
}
private:
void foo() { cout << "foo()" << endl; }
void bar(const string& s) { cout << "bar(" << s << ")" << endl; }
void baz(int i) { cout << "baz(" << i << ")" << endl; }
map<string, any> calls;
};
int main() {
VarCall v;
v.call("Alice"); //prints foo()
v.call("Bob", "2"); //prints bar(2)
v.call("Charlie", 1); //prints baz(1)
return 0;
}