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?
A key advantage of lambdas is they can reference member functions statically, while bind can only reference them through a pointer.
Why Use Lambda Functions? Lambda functions are used when you need a function for a short period of time. This is commonly used when you want to pass a function as an argument to higher-order functions, that is, functions that take other functions as their arguments.
Bind function arguments. Returns a function object based on fn , but with its arguments bound to args . Each argument may either be bound to a value or be a placeholder: - If bound to a value, calling the returned function object will always use that value as argument.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With