Search code examples
c++stdmappointer-to-member

how to call member function from map of classes


I'm trying to call member function through a map of member function ptr that is a data member of a different class

{    
    class B
    {
    public:
    typedef void (B::*funcp)(int);
    B()
    {
        func.insert(make_pair("run",&B::run));
    }
        void run(int f);
        map<string,funcp>func;
    };

    class A
    {
        public:
        A();
        void subscribe(B* b)
        {
            myMap["b"] = b;
        }
        map<string,B*>myMap;
        void doSome()
        {
             myMap["place"]->func["run"](5);
        }
    };
    int main()
    {
        A a;
        B b;
        a.subscribe(&b);
        a.doSome();
        return 0;
    }
}

but im getting

error: must use ‘.’ or ‘->’ to call pointer-to-member function in ‘((A*)this)->A::myMap.std::map, B*>::operator[](std::basic_string(((const char*)"place"), std::allocator()))->B::func.std::map, void (B::)(int)>::operator[](std::basic_string(((const char)"run"), std::allocator())) (...)’, e.g. ‘(... ->* ((A*)this)->A::myMap.std::map, B*>::operator[](std::basic_string(((const char*)"place"), std::allocator()))->B::func.std::map, void (B::)(int)>::operator[](std::basic_string(((const char)"run"), std::allocator()))) (...)’

i also tryed :

{
    auto p = myMap["place"];
    (p->*func["run"])(5);
}

and thien the error it:

‘func’ was not declared in this scope


Solution

  • B* bptr = myMap["place"];
    (bptr->*(bptr->func["run"]))(5);
    

    OK tested now, and thanks to Sombrero Chicken for fixing the typos. You don't need all those parens, but it's probably a good idea to leave them in.

    The thing you are missing is that you need your B pointer twice. Once to find the map in the other object, and once to call the member function using the member function pointer.