Writing an inline nullary function object?
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
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
g = f; but without defining the intermediate f()?
I thought this might work...
boost::function
g = bind(bind(apply<int>(), _1 ), x );
With Lambda, you could write:
boost::function
On Wed, Dec 1, 2010 at 6:35 PM, Eric MALENFANT < Eric.Malenfant@sagem-interstar.com> 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
g = f; but without defining the intermediate f()?
I thought this might work...
boost::function
g = bind(bind(apply<int>(), _1 ), x ); With Lambda, you could write: boost::function
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 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.
Using lambda::var is a good trick. I usually used this:
bind(ref, x)
It works, but I always find it kind a ugly.
Thanks for the pointer :)
--- Pada Rab, 1/12/10, 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
g = f;
but without defining the intermediate f()?
I thought this might work...
boost::function
g = bind(bind(apply<int>(), _1 ), x );
With Lambda, you could write:
boost::function
On Thu, Dec 2, 2010 at 9:36 AM, Kamil Zubair
Using lambda::var is a good trick. I usually used this:
bind(ref, x)
It works, but I always find it kind a ugly. Thanks for the pointer :)
--- Pada *Rab, 1/12/10, Robert Jones
* menulis:
Actually I kinda like your version, that was exactly the incantation I'd been looking for, as I'd prefer not to pull in the Lambda headers. Thx - Rob.
participants (3)
-
Eric MALENFANT
-
Kamil Zubair
-
Robert Jones