Passing class instance and method as argument to another function in C++

I have two classes. One class has a method that takes a function as a parameter and that passed function is expected to have a string as an argument. For example:

class Dog{
public:
    void doDogThings(std::function <void(std::string)> theFunction);

}

class Cat{
public:
    void doCatThings(std::string stringInput);
}

And here they are in action

int main(){
   Cat aCat;
   Dog aDog;
   std::string theString = "Oh jeez";
   aDog.doDogThings(<< insert cat's method and argument here >>);
   .....

This is the part that is fouling me up here; I know I should use

bind(&Cat::doCatThings, ref(aCat) ....?.....);

But I am stuck on how to pass the argument for the Cat method as a parameter to this function pointer. Any help would be greatly be appreciated. Thanks.

1 answer

  • answered 2018-02-13 02:44 aschepler

    The correct bind syntax would be:

    aDog.doDogThings(std::bind(
        &Cat::doCatThings, std::ref(aCat), std::placeholders::_1));
    

    The "placeholder" _1 means "the first argument to the resulting functor will get used here to pass to the bound callable".

    But I really don't recommend using std::bind in almost any circumstance. It has some annoying gotchas, is often tricky to get correct, tricky to read again after you've written a use of it, and results in the most terrible compiler errors any time you get something slightly wrong. Lambdas can do anything std::bind can do and quite a bit more, without most of those problems.

    So instead, I'd suggest:

    aDog.doDogThings(
        [&aCat](std::string stringInput)
        { aCat.doCatThings(std::move(stringInput)); }
    );