Bind vs. Lambda: Exploring Their Differences and Suitability
In C 0x, developers have the option of utilizing either lambda expressions or std::bind to accomplish certain programming tasks. While both techniques share some commonalities, their suitability in specific scenarios may differ significantly.
Intersecting Functionality Example
Let's consider an example of intersecting functionality between lambda and bind. Suppose we have a requirement to generate random numbers using an engine. Using a lambda, we can encapsulate the necessary logic as follows:
<code class="cpp">uniform_int<> distribution(1, 6); mt19937 engine; // lambda style auto dice = [&]() { return distribution(engine); };</code>
Alternatively, using std::bind, we can achieve the same result:
<code class="cpp">uniform_int<> distribution(1, 6); mt19937 engine; // bind style auto dice = bind(distribution, engine);</code>
Monomorphism vs. Polymorphism
A key distinction between lambda expressions and std::bind lies in their polymorphism capabilities. Lambda expressions in C 0x are monomorphic, meaning their arguments must have known types. This limitation can be encountered when working with generic functions that accept arguments of varying types.
For instance, consider the following lambda:
<code class="cpp">auto f = [](auto a, auto b) { cout << a << ' ' << b; }
Using this lambda requires specifying the types of a and b at compile time. This can be a restriction in situations where the types are not known in advance.
In contrast, std::bind allows for polymorphic behavior. Utilizing Phoenix/lambda bind, developers can define functions that accept arguments of varying types, as demonstrated in the example below:
<code class="cpp">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);</code>
In this case, the types of the arguments a and b are deduced at runtime, providing greater flexibility.
Advantages and Disadvantages
To summarize the advantages and disadvantages of each approach:
Lambda Expressions:
std::bind:
Conclusion
The choice between std::bind and lambda expressions in C 0x depends on the specific requirements of the application. For monomorphic scenarios, lambdas offer a convenient and concise approach. For polymorphic scenarios where argument types can vary dynamically, std::bind provides greater flexibility. Understanding the strengths and weaknesses of both techniques allows developers to make informed decisions when crafting their code.
The above is the detailed content of Lambda vs. `std::bind`: When Should You Use Each in C ?. For more information, please follow other related articles on the PHP Chinese website!