I used to use std::bind very often for partially or fully binding a function and pass the bound function to other functions, such as performance profiling. However, recently I spent lots of time only to realize that std::bind cannot be used wherever I want to. In contrast, lambda expressions are more flexible and can be used to replace std::bind.
In this blog post, I would like to discuss std::bind versus lambda expressions in C++.
C++ Bind VS Lambda
In the following example, we could see that std::bind does not seem to be applicable for the functions that have been overloaded. At least I am not aware of any solution that allows std::bind to be used for an overloaded function. In contrast, lambda expressions can work with overloaded functions and mimic the partial binding behaviors that std::bind has.
// Bind the Foo::print_n to foo. std::function<void()> const foo_print_n_bind{ std::bind(&Foo::print_n, &foo)}; // Call the member function print_n. foo_print_n_bind(); // Create a lambda expression that calls foo's member function print_n. std::function<void()> const foo_print_n_lambda{[&foo]() { foo.print_n(); }}; // Call the lambda expression. foo_print_n_lambda();
// The same std::bind implementation does not work for Bar::print_n because // it's overloaded. error: no matching function for call to // ‘bind(<unresolved overloaded function type>, const Bar*)’ // std::function<void()> const bar_print_n_bind{ // std::bind(&Bar::print_n, &bar)}; // bar_print_n_bind(); // Create a lambda expression that calls bar's member function print_n. // This still works. std::function<void()> const bar_print_n_lambda{[&bar]() { bar.print_n(); }}; bar_print_n_lambda(); std::function<void()> const bar_print_n_lambda_line_break{ [&bar]() { bar.print_n(true); }}; bar_print_n_lambda_line_break();
// Use std::bind inside Baz::print_n_bind. baz.print_n_bind(); // Use lambda inside Baz::print_n_lambda. baz.print_n_lambda();
// Use lambda inside Qux::print_n_lambda. qux.print_n_lambda(); // Use lambda inside Qux::print_n_lambda(bool). qux.print_n_lambda(true);