c++return-typepointer-to-membermember-functions

Member function that takes member function as parameter


I have one class Hunter that has a member function random_hunt which returns a pair<int, int> const that's supposed to be equivalent to some point (x, y). I'm trying to implement a second member function test_hunt which will return the number of tries it takes the random_hunt to land on a target point given the target pair, the member function itself, and the class itself.

I have attempted two implementations:

class Hunter {
        // 1
    int test_hunt(std::function<pair<int, int> const()> func, pair<int, int>& const target) {
        int tries = 0;
        while (target != func())
            tries++;
        return tries;
    }

        // 2
    int test_hunt(pair<int, int> const (Hunter::* func)(), Hunter& hunter, pair<int, int>& const target) {
        int tries = 0;
        while (target != (hunter.*func)())
            tries++;
        return tries;
    }
};

in main:

Hunter hunter;

auto fp = std::bind(&Hunter::random_hunt);
std::cout << hunter.test_hunt(fp, r_start_pos) << '\n';

std::cout << hunter.test_hunt(&Hunter::random_hunt, hunter, r_start_pos) << '\n;

Neither compile and I'm not sure why. I've looked at previous examples that do something similar using member functions of void return type and they seem to work fine. Is it the return type in my case that's making the difference, or have I simply implemented the function incorrectly?


Solution

  • With std::bind you need to pass object pointer as well along with method, like

     auto fp = std::bind(&Hunter::random_hunt,&hunter);
    

    Here is compiled code.