Boost logo

Boost Users :

Subject: Re: [Boost-users] Writing an inline nullary function object?
From: Eric MALENFANT (Eric.Malenfant_at_[hidden])
Date: 2010-12-01 13:35:16


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.


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