I'm new to C++11 lambdas and would like to turn a binary lambda into a unary one by binding its second parameter:
auto lambda1 = [] (int a, int b) { return a+b; };
auto lambda2 = std::bind2nd(lambda1, 5);
Compilation fails with
error: no type named 'first_argument_type' in 'struct main(int, char**)::<lambda(int, int)>'
class binder2nd
[How] can this be done?
Just like a normal function, a Lambda function can have multiple arguments with one expression. In Python, lambda expressions (or lambda forms) are utilized to construct anonymous functions. To do so, you will use the lambda keyword (just as you use def to define normal functions).
Lambda expressions Like anonymous functions, lambda expressions allow no default parameters and cannot be called with named arguments. Since they are stored immediately as a function type like (Int, Int) -> Int , they undergo the same restrictions as function types referring to actual functions.
In Kotlin, the lambda expression contains optional part except code_body.
If you already employ lambda expressions, just use another one:
auto lambda2 = [&] (int i) {return lambda1(i, 5);};
#include <functional>
int main(int argc, char *argv[])
{
auto lambda1 = [](int a, int b) { return a+b; };
auto lambda2 = std::bind(lambda1, std::placeholders::_1, 5);
// ~~~~~~~^^^^~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^~~~
return 0;
}
Demo
Also prefer to use std::bind
over std::bind1st
and std::bind2nd
since both were deprecated in C++11 and are scheduled to be removed in C++17.
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