Search code examples
c++stdmappointer-to-member

function pointer - Expression preceding parentheses of apparent call must have (pointer-to-) function type


I have a class:

#include<map>

class myclass {
public:

    typedef std::map<std::string, int(myclass::*)()> mymap;

    void Foo() {
        UpdateMap();
        mymap1["AddToa"]();
        mymap1["AddTob"]();
    }


private:
    int a;
    int b;

    mymap mymap1;

    int AddToa(){ std::cout<< "add 2 to a: " << a+2 << std::endl;};
    int AddTob(){ std::cout<< "add 2 to b: " << b+2 << std::endl;};

    void UpdateMap(){
        mymap1["AddToa"] = &myclass::AddToa;
        mymap1["AddTob"] = &myclass::AddTob;
    }
};

But In Foo(), when I'm trying to call these 2 function via their pointers:

mymap1["AddToa"]();

I get this compilation error:

expression preceding parentheses of apparent call must have (pointer-to-) function type

what should I do?


Solution

  • You seem to want to call the member function pointer on the current class.

    (this->*mymap1["AddToa"])();
    

    Resaerch member access operators.