Boost logo

Boost Users :

From: Douglas Paul Gregor (gregod_at_[hidden])
Date: 2004-06-17 11:54:46

On Thu, 17 Jun 2004, Eduardo Bezerra wrote:

> Hi,
> I need to use boost::function in a context like this one:
> struct Widget {
> string ToString() {return "Widget"; }
> };
> int main()
> {
> function<string () f(&Widget::ToString);
> }
> What's the correct syntax to sucessfully compile this example ?

To call the ToString() method, you need to have an object of type Widget.
In the code above, there is no such object, so it fails to compile. There
are two options:
  (a) You want to pass a pointer/reference to the widget into the
boost::function object so "f" can work on any widget, or
  (b) You want to store a pointer/reference to a particular widget and
pass nothing to the boost::function object "f".

For (a), you need only specify whether you want to pass in a pointer or a
reference, e.g.,

int main()
  function<string (Widget*)> f(&Widget::ToString);

  Widget w;
  f(&w); // returns "Widget"

For (b), you'll need to use another Boost library (Bind) to store a
pointer to a widget along with the member pointer for ToString:

int main()
  Widget w;

  function<string()> f(boost::bind(&Widget::ToString, &w));

  f(); // returns "Widget"


Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at