I have a question about which style is preferred: std::bind Vs lambda in C++0x. I know that they serve -somehow- different purposes but lets take an example of intersecting functionality.
Using lambda
:
uniform_int<> distribution(1, 6);
mt19937 engine;
// lambda style
auto dice = [&]() { return distribution(engine); };
Using bind
:
uniform_int<> distribution(1, 6);
mt19937 engine;
// bind style
auto dice = bind(distribution, engine);
Which one should we prefer? why? assuming more complex situations compared to the mentioned example. i.e. What are the advantages/disadvantages of one over the other?
C++0x lambdas are monomorphic, while bind can be polymorphic. You cannot have something like
auto f = [](auto a, auto b) { cout << a << ' ' << b; }
f("test", 1.2f);
a and b must have known types. On the other hand, tr1/boost/phoenix/lambda bind allows you to do this:
struct foo
{
typedef void result_type;
template < typename A, typename B >
void operator()(A a, B b)
{
cout << a << ' ' << b;
}
};
auto f = bind(foo(), _1, _2);
f("test", 1.2f); // will print "test 1.2"
Note that the types A and B are not fixed here. Only when f is actually used these two will be deduced.