Boost logo

Boost Users :

From: Paul Elliott (pelliott_at_[hidden])
Date: 2004-11-27 21:47:21


The bind documentation mentions the apply object as a way
to get around the fact that bind does not evaluate its
first arguement.

There is another use. You can reverse the roles of function and
parameters. You can use apply and bind to turn a parameter
into a functor, and call it using a function as a parameter!

Example.

#include <boost/bind.hpp>
#include <boost/function.hpp>

#include <boost/bind/apply.hpp>

#include <fstream>
#include <iostream>
#include <iomanip>

// some sample test functions. (data)
int g(int x) {return x+1;};
int h(int x) {return x*x; };

int main(int argc, char * argv)
{

  // want to work with functions of the form int f(int);
  typedef int P(int);

  // bind the integer 5 to apply turning
  // apply into the number 5 into a function! call it five
  boost::function<int (P)> five =
        boost::bind(boost::apply<int>(),_1,5);
    

  //int y = five(g);

  // Now call 5 with the "data" g and h.

       std::cout << "+1=" << five(g) << std::endl
            << "square = " << five(h) << std::endl;

  return 0;
  
};

Results:
+1=6
square = 25

-- 
Paul Elliott                       1(512)837-1096
pelliott_at_[hidden]                    PMB 181, 11900 Metric Blvd Suite J
http://www.io.com/~pelliott/pme/   Austin TX 78758-3117



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