Pages

boost::lambda::placeholder and more

The C++0x simplify a lot the usage of the lambda expression still, if you are using a compiler that does not support it yet, it useful to know a couple of tricks that could help us in keeping the code more readable.

For instance, using constant_type<>::type could we define constant to be used in our expression, besides, we see here also how to redefine the name for the placeholders:

#include <iostream>
#include <vector>
#include <algorithm>

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

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

namespace
{
template <typename T, typename Operation>
void for_all(T& t, Operation op) { std::for_each(t.begin(), t.end(), op); }

template<typename T>
void lambdaBoost(const T& t)
{
using namespace boost::lambda;

constant_type<char>::type space = constant(' ');
boost::lambda::placeholder1_type _;

boost::function<void(T::value_type)> f = cout << _ << space;
for_all(t, f);
cout << endl;
}

template<typename T>
void lambda0x(const T& t)
{
auto f = [] (T::value_type x) { cout << x << ' '; } ;
for_all(t, f);
cout << endl;
}
}

void lambda04()
{
std::vector<int> v;
for(int i = 0; i < 5; ++i)
v.push_back(i);

lambdaBoost(v);
lambda0x(v);
}


For more information on boost lambda you could read "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book.

No comments:

Post a Comment