1

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;
}
merula
  • 384
  • 2
  • 8
  • Always post the complete error(if any) along with your code, always. – Jason May 26 '23 at 13:01
  • @merula The question has been closed but I'm not sure that the linked answer is sufficient for your issue as it concerns member functions. Can you confirm that it's solved? – Oersted May 26 '23 at 13:38
  • question completed [there](https://stackoverflow.com/questions/76341673/correct-way-to-store-a-pointer-to-member-function-inside-stdany) – Oersted May 27 '23 at 09:29

0 Answers0