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

1
  • Why not std::function? It was added to the standard. Commented May 29, 2015 at 5:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

what is the meaning or the function of the "void" in boost::function<void (Dog*, int, dogfood*)> f2 = &Dog::bark2; ?
@user2162793 It represents the return type of the function
but bark2 returns int: int bark2(int a, dogfood *b)
ohhh I made a typo then. The code compiles because std:function greedily accepts almost everything. Thanks for pointing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.