Boost logo

Boost Users :

From: Stuart Dootson (stuart.dootson_at_[hidden])
Date: 2007-10-12 14:55:29


On 12/10/2007, Peter Waller <peter.waller_at_[hidden]> wrote:
> I wish to write some lambda functions to have this sort of behaviour.
>
> #include <lambda/lambda.hpp>
> #include <lambda/bind.hpp>
> #include <function.hpp>
>
> using namespace boost::lambda;
> using namespace boost;
>
> #include <iostream>
> using std::cout; using std::endl;
>
> #include <cmath>
>
> int main( int argc, char *argv[] )
> {
> float value;
> var_type<float>::type theValue( var( value ) );
>
> // Ignore this line
> #define cos(theta) bind( unlambda(bind( cos, _1 )), theta )
>
> function<float ( float )> myfunction = ( cos( theValue ) - 1 );
> value = 2;
> cout << "The result = " << myfunction(1) << endl;
> return 0;
> }
>
> Namely, the cos( value ) part.
>
> The code above works, but I feel that using a #define is a little
> messy, and seems hard to generalise to functions with more arguments.
> I was wondering if there was a general, better way of turning a given
> function into one whose execution is delayed.
>
> Thanks in advance,
>
> - Peter

This seems to work:

   double value = 3.14159 / 2.0;
   boost::function<float(void)> fn =
bind(static_cast<double(*)(double)>(&cos), var(value));
   std::cout << fn() << std::endl;
   value = 0.0;
   std::cout << fn() << std::endl;

At least, the output of 'fn()' changes when 'value' changes, which (as
far as I could tell) was what you wanted?

The static_cast is needed to select the appropriate 'cos' overload.

HTH

Stuart Dootson


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