2

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?

  • 2
    you need an object of `myclass` to call a member function of `myclass` – 463035818_is_not_an_ai Jun 29 '21 at 08:00
  • As @463035818_is_not_a_number suggests, you can't add the member function of 'myclass' to the map, because no instance of that class exists. What are you actually trying to achieve by adding member functions to the map? They're already accessible within the class – Ryan Pepper Jun 29 '21 at 08:02
  • @RyanPepper thats not what I was suggesting! One can add pointers to the member functions to the map. The problem is only in how OP is trying to call them – 463035818_is_not_an_ai Jun 29 '21 at 08:03
  • @463035818_is_not_a_number learn something new every day! Still not sure why you'd want to do it though... i'm wondering if it's because the poster wants to access private member functions publicly? – Ryan Pepper Jun 29 '21 at 08:09
  • @RyanPepper the map allows you to select a member function based on a string. That has many uses. Its actually rather cool stuff, you should experiment with it – 463035818_is_not_an_ai Jun 29 '21 at 08:12
  • @463035818_is_not_a_number very clever! – Ryan Pepper Jun 29 '21 at 08:17

1 Answers1

3

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

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

Resaerch member access operators.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • thanks! can you please explain the syntax? I dont understand why * is needed if the function pointer is followed by (). when invoking regular non member function by its pointer, it works... – New programmer Jun 29 '21 at 08:22
  • There is a link I posted - cppreference explains the operators. Here are some c++ books https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list . `can you please explain the syntax?` it's like addition `a + b` has the same syntax as `a ->* b`. `I dont understand why *` that's part of the operator `->*` just like `=` is part of `+=`. `when invoking regular non member function by its pointer` For non-member function pointers you do not need a class to call them on. – KamilCuk Jun 29 '21 at 08:27