Pages

A boost::bind for any function

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.

It's easy to use boost::bind for any function. Let's see an example where bind refers to a free function, a static member function, and a member function.

Notice that a member function could be called for an existing object, or we could create the object on the fly, and in this latter case we could use the nullary functor, that means, also the parameter for the object is passed directly as parameter to bind:

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

using std::string;
using std::cout;
using std::endl;
using boost::bind;

namespace
{
class AClass
{
public:
void printString(const string& s) const {
cout << "Member function: " << s << endl;
}

static void staticPrintString(const string& s) {
cout << "Static member function: " << s << endl;
}
};
}

void printString(const string& s)
{
cout << "Free function: " << s << endl;
}

void bind02()
{
bind(&printString, _1)("Hello!");

bind(&AClass::staticPrintString, _1)("Hello!");

AClass c;
bind(&AClass::printString, _1, _2)(c, "Hello!");

bind(&AClass::printString, AClass(), _1)("Hello!");

cout << "Nullary" << endl;
bind(&AClass::printString, AClass(), "Hello!")();
}

No comments:

Post a Comment