The “solution” below compiles but it is not what I want. I would like to pass the put member function to for_each and not *this. Using boost is NOT an option. Can this be solved within C++03?
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
class Wheel { };
class Car {
public:
void process(const vector<Wheel>& wheel) {
for_each(wheel.begin(), wheel.end(), *this);
}
void operator()(const Wheel& w) { put(w); }
private:
void put(const Wheel& w) { }
};
int main() {
vector<Wheel> w(4);
Car c;
c.process(w);
return 0;
}
Yes it can, using a combination of the
mem_funandbind1sttemplates:The call to
mem_funcreates a new function object that takes in two arguments – aCar*to act as the receiver and aWheel, then callsputwith the first parameter as the receiver and the second parameter as the argument. Callingbind1stthen locks the receiver object as first parameter of this function in place.However, I think you will need to make one small change to this code to get it to work. The
bind1stadapter doesn’t play well with functions that take their arguments by const reference, so you might need to changeputso that it takes aWheelby value rather than by reference.