Re: Functor adaptor question
Tim Roberts a =E9crit :
I had a case today where I needed a functor that was a bound member
function. Basically:
class MyClass {
...bug free code omitted...
void PrintMe( int x ) {
printf( "%d\n", x );
}
void A_Function() {
...
std::vector<int> myList;
...
std::for_each(
myList.begin(),
myList.end(),
bound_mem_fun( *this, PrintMe ); // bound_mem_fun is made up
);
}
Am I correct in my conclusion that there is no such adapter in the standa=
rd
library? It looks like there is one in Boost, and it only took about 8
lines of code to implement it, but I don't want to reimplement it if there
is one built in that I missed.
You can do it with the standard library "mem_fun" facility, but it is
really clumsy, and you should prefer boost::bind if you can (btw, I
think boost::bind has been intergrated in CR1, so it will be part of
"official" C++ quite soon).
The STL version read like this:
for_each(myList.begin(), myList.end(),
bind1st (mem_fun1<void, MyClass ,int>(&MyClass::PrintMe),
this));
The boost version reads like this (ans it takes only 1 line!) :
#include <boost/bind.hpp>
using namespace boost;
.....
for_each(myList.begin(), myList.end(),
bind(&MyClass::PrintMe, this, _1));
Arnaud
MVP - VC