Home > Article > Backend Development > Lambdas vs. Bind in C : When Should You Choose Each?
Lambdas vs. Bind in C : Polymorphism and Efficiency
When comparing the usage of C 0x lambdas and std::bind for similar tasks, the choice between the two can be influenced by factors such as polymorphism and efficiency.
Bind vs. Lambda in Detail
Consider the following example where both lambda and bind are used to generate random numbers using a distribution and engine:
// Using lambda auto dice = [&]() { return distribution(engine); }; // Using bind auto dice = bind(distribution, engine);
Polymorphism
Unlike lambdas, which are monomorphic (i.e., have fixed types), std::bind allows for polymorphic behavior. This means that bind can be used to create functions with unknown types, as demonstrated below:
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"
In this example, the types of a and b are deduced at runtime when f is invoked. This flexibility is unavailable with lambdas.
Efficiency
In general, lambdas tend to be more efficient than bind when the captured variables are used by value. This is because lambdas capture variables directly, while bind creates a closure object that references the captured variables. However, bind may offer advantages when the captured variables are large or when the function is called frequently.
Conclusion
The choice between lambdas and bind depends on the specific requirements of the application. Lambdas provide polymorphism and are efficient for capturing small, value-type variables. Bind offers greater flexibility and may be preferable when dealing with large or frequently called functions.
The above is the detailed content of Lambdas vs. Bind in C : When Should You Choose Each?. For more information, please follow other related articles on the PHP Chinese website!