Home > Article > Backend Development > When to Choose: std::bind vs. Lambdas in C 0x?
Compare and Contrast: std::bind and Lambdas in C 0x
In C 0x, programmers are faced with two options for capturing a function: std::bind and lambdas. While both serve distinct purposes, they overlap in some applications. Let's delve into the strengths and limitations of each approach, taking an example of intersecting functionality.
Consider the task of creating a dice-rolling function. Using lambda, we can express this as:
<code class="cpp">auto dice = [&]() { return distribution(engine); };</code>
Alternatively, using std::bind, we can write:
<code class="cpp">auto dice = bind(distribution, engine);</code>
Monomorphic vs. Polymorphic
One fundamental distinction lies in their type behavior. Lambdas are monomorphic, meaning they have fixed argument types determined at compile time. This constraint limits the flexibility of lambdas compared to their bind counterparts.
For instance, consider a function that prints two arguments:
<code class="cpp">auto f = [](auto a, auto b) { cout << a << ' ' << b; }
Using this lambda with different parameter types will result in a compiler error. In contrast, std::bind allows for polymorphic behavior, enabling the function to be bound to arguments of varying types:
<code class="cpp">struct foo { template <typename A, typename B> void operator()(A a, B b) { cout << a << ' ' << b; } }; auto f = bind(foo(), _1, _2);</code>
By deferring type deduction until the function is invoked, std::bind offers greater flexibility for handling diverse input types.
The above is the detailed content of When to Choose: std::bind vs. Lambdas in C 0x?. For more information, please follow other related articles on the PHP Chinese website!