Pages

Constants inside a lambda expression

Using constants inside a boost lambda expression is a kind a nuisance. And also calling a member for a variable passed to the lambda expression is not so smooth as it could be.

This is not an issue anymore, if you are lucky enough to use a compiler that supports the C++0x TR1. But if this is not the case, well, just be patient.

Here is an example that shows the difference between the two implementations:

#include <iostream>
#include <string>
#include <map>
#include <algorithm>

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

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

namespace
{
typedef std::map<int, std::string> AMap;

void lambdaBoost(const AMap& aMap)
{
using namespace boost::lambda;

cout << "boost lambda nullary functor: constant()\n";
for_each(aMap.begin(), aMap.end(),
cout << constant("key = ") << bind(&AMap::value_type::first, _1)
<< ", value = " << bind(&AMap::value_type::second, _1) << '\n');

// Print the size and max_size of the container
(cout << "size is = " << bind(&AMap::size, _1)
<< "\nmax_size is = " << bind(&AMap::max_size, _1) << '\n')(aMap);
}

void lambdaOx(const AMap& aMap)
{
cout << endl << "C++0x lambda makes it easier" << endl;
typedef AMap::value_type AMType;
auto f1 = [] (AMType at) { cout << "key = " << at.first << ", value = " << at.second << endl; };
for_each(aMap.begin(), aMap.end(), f1);

[aMap] { cout << "size is = " << aMap.size() << endl << "max_size is = " << aMap.max_size() << endl; } ();
}
}

void lambda02()
{
AMap aMap;
aMap[3] = "Less than pi";
aMap[42] = "You tell me";
aMap[0] = "Nothing, if you ask me";

lambdaBoost(aMap);
lambdaOx(aMap);
}

As we see, the boost implementation of lambda requires our collaboration, since we have to use the constant() function to mark at least the first string used in the expression as a constant, and we should explicitly bind() the variable to access a member of it.

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