0

I would like to implement an std::map with <std::string, std::function> pairs. The function pointers are pointers to methods of the class. I am thinking of ignoring a switch or an equivalent so trying this. But I am able to use only static member functions. Compiler is throwing error C3867: 'A::m2': non-standard syntax; use '&' to create a pointer to member for non static member function. Any better approach or idea to implement my approach?

#include <iostream>
#include <unordered_map>
#include <string>
#include <functional>

class A
{
public:
    static void m1() { std::cout << "Method1\n"; };
    void m2() { std::cout << "Method2\n"; };
};

int main(int argc, char const* argv[])
{
    if (argc > 1)
    {
        A a;
        std::unordered_map<std::string, std::function<void()>> methodMap = 
        {
            {"f1", a.m1},
            {"f2", a.m2}
        };

        auto it = methodMap.find(argv[1]);
        if (it != methodMap.end())
            it->second();
    }
}
Arun
  • 2,247
  • 3
  • 28
  • 51

0 Answers0