Boost logo

Boost Users :

Subject: Re: [Boost-users] Writing an inline nullary function object?
From: Robert Jones (robertgbjones_at_[hidden])
Date: 2010-12-01 17:22:12


On Wed, Dec 1, 2010 at 6:35 PM, Eric MALENFANT <
Eric.Malenfant_at_[hidden]> wrote:

> De : Robert Jones
> > How can I write an inline nullary function object, returning a fixed
> > value? The equivalent of this...
> >
> > int x = 4;
> >
> > int f( ) { return x; }
> >
> > boost::function<int()> g = f;
> >
> > but without defining the intermediate f()?
> >
> > I thought this might work...
> >
> > boost::function<int()> g = bind(bind(apply<int>(), _1 ), x );
> >
>
> With Lambda, you could write:
> boost::function<int()> g = boost::lambda::constant(4);
> or, if you want to refer to a variable, and have g() return the *current*
> value of that variable:
> int i = 4;
> boost::function<int()> g = boost::lambda::var(i);
> assert(g() == 4);
> i = 5;
> (assert(g() == 5);
>
> I'm not aware of something equivalent for Bind, however.
>

Eric, many thanks for that - I just about got there on my own, but it's good
to have it confirmed, especially that there's no Bind equivalent. I've now
found the
line the Lambda docs which says,

"In sum, var(x) creates a nullary lambda functor, which stores a reference
to the variable x. When the lambda functor is invoked, a reference to x is
returned."

Which is exactly the answer I was looking for.

- Rob.



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net