Pages

Calling a member function via boost::bind and C++0x lambda

As an introduction to some of the most interesting boost libraries you can read "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. That's what I'm actually doing, and these are a few notes that I'm jotting down in the meanwhile.

If your compiler is one that already supports the C++0x lambda, is probabibly better forgetting about boost:bind and using lambda (that is really cool). In any case, it is useful to know how to tackle a problem using different approach.

The following example shows how to call a member function inside a for_each call using the STL mem_fun_ref adaptor, boost::bind, and C++0x lambda:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include "boost/bind.hpp"

using std::string;
using std::cout;
using std::endl;
using std::vector;
using std::for_each;
using std::mem_fun_ref;
using boost::bind;

namespace
{
class status
{
std::string name_;
bool ok_;
public:
status(const string& name) : name_(name), ok_(true) {}
void breakIt() { ok_ = false; }
bool isBroken() const { return ok_; }
void report() const { cout << name_ << " is " << (ok_ ? "up" : "down") << endl; }
};
}

void bind01()
{
vector<status> statuses;
statuses.push_back(status("status 1"));
statuses.push_back(status("status 2"));
statuses.push_back(status("status 3"));
statuses.push_back(status("status 4"));

statuses[1].breakIt();
statuses[2].breakIt();

cout << "Using a classic for loop" << endl;
typedef vector<status>::iterator IT;
for (IT it = statuses.begin(); it != statuses.end(); ++it)
it->report();

cout << "Using for_each and mem_fun_ref" << endl;
for_each(statuses.begin(), statuses.end(), mem_fun_ref(&status::report));

cout << "Using for_each and boost::bind" << endl;
for_each(statuses.begin(), statuses.end(), bind(&status::report, _1));

cout << "Using for_each and C++0x lambda" << endl;
for_each(statuses.begin(), statuses.end(), [](status s){s.report();});
}

No comments:

Post a Comment