Pages

The lambda expression

A lambda expression is a sort of function, that is declared in the body of another function and that could also be used in a boost::function (and even a std::function, if your compiler already support the C++0x TR1 ).

Here is a simple example that shows how to use a lambda expression, alone and in combination with function, using the boost libraries:

#include <iostream>

#include "boost/lambda/lambda.hpp"
#include "boost/function.hpp"

using namespace boost::lambda;
using std::cout;
using std::endl;

void boostLambda()
{
cout << "boost::lambda says hello ..." << endl;

(cout << _1 << " " << _3 << " " << _2 << "!\n") ("Hello", "friend", "my");

boost::function<void(int,int,int)> f =
cout << _1 << "*" << _2 << "+" << _3 << " = " << _1*_2+_3 << "\n";

f(1, 2, 3);
f(3, 2, 1);
}

The boost implementation is a bit different from the standard one, but it works just in the same way:

#include <iostream>
#include <functional>

using std::cout;
using std::endl;

void stdLambda()
{
cout << endl << "C++0x lambda says hello ..." << endl;

[] (char* a, char* b, char* c) { cout << a << ' ' << c << ' ' << b << '!' << endl; }("Hello", "friend", "my");

std::function<void(int,int,int)> f =
[] (int a, int b, int c) {cout << a << "*" << b << "+" << c << " = " << a*b+c << endl;};

f(1, 2, 3);
f(3, 2, 1);
}

The standard implementation is a bit more verbose than the boost one or we could say that the standard way is a bit more explicit.

In my opinion the standard version is more readable, but this is just a matter of taste.

The code is based on an example provided by "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. An interesting reading indeed.

No comments:

Post a Comment