0

I came across the following code where Foo is any user-defined class:

boost::function<return_type (parameter)> f = boost::ref(instanceOfFoo);

And I have the following Qs: 1. What happens if you assign an instance of a class to the boost function pointer? I thought we could only assign functions to it. 2. Why is the boost ref sent and not just the value?

1 Answer 1

1
  1. boost::function (and C++11's std::function) wrap callable objects, which are any object that can be invoked like a function. This includes both ordinary functions and functors. A functor is a class or struct that that defines operator().

  2. The boost::function documentation explains why you might want to wrap a reference to a functor instead of the function itself:

In some cases it is expensive (or semantically incorrect) to have Boost.Function clone a function object. In such cases, it is possible to request that Boost.Function keep only a reference to the actual function object. This is done using the ref and cref functions to wrap a reference to a function object:

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

2 Comments

So effectively, assigning a functor instance to a boost function pointer is like assigning the operator()() "function" to it? Thanks
Yes, but take note that you are binding not only the operator() member function but also the member variable state of the instance that the function may use.

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.