2

I want to use pointers to a class method using boost, I saw this answer in stackoverflow that has an example of using boost:

Calling C++ class methods via a function pointer

However when I am trying to add a more complicated function,I don't know how to call it using boost: How can I call the bark2 function in a similar way that bark1 is called?

struct dogfood
{
    int aa;
};

class Dog
{
public:
    Dog(int i) : tmp(i) {}
    void bark()
    {
        std::cout << "woof: " << tmp << std::endl;
    }

    int bark2(int a, dogfood *b)
    {
        return(6);
    }
private:
    int tmp;
};

int main()
{
   Dog* pDog1 = new Dog (1);
   Dog* pDog2 = new Dog (2);

   //BarkFunction pBark = &Dog::bark;
   boost::function<void (Dog*)> f1 = &Dog::bark;

   f1(pDog1);
   f1(pDog2);
}

Thanks

Community
  • 1
  • 1
user2162793
  • 55
  • 2
  • 8

1 Answers1

2

Use

boost::function<int (Dog*, int, dogfood*)> f2 = &Dog::bark2;

and call it like

f2(pDog2, 10, nullptr); // or pass the required pointer

BTW, in C++11 you can simply use std::function from #include <functional> instead. Alternatively, you can use std::mem_fn (also since C++11), like

auto f3 = std::mem_fn(&Dog::bark2);
f3(pDog2, 42, nullptr);

The latter is a thin wrapper around a pointer-to-member-function and should probably perform better than the more "heavier" std::function.

vsoftco
  • 55,410
  • 12
  • 139
  • 252