Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to bind the second parameter of a lambda function?

Tags:

c++

c++11

lambda

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?

like image 433
oarfish Avatar asked Nov 29 '15 18:11

oarfish


People also ask

Can lambda take two arguments?

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).

When a lambda function has only one parameter what is its default name?

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.

Which is not optional in lambda functions?

In Kotlin, the lambda expression contains optional part except code_body.


2 Answers

If you already employ lambda expressions, just use another one:

auto lambda2 = [&] (int i) {return lambda1(i, 5);};
like image 96
Columbo Avatar answered Oct 02 '22 16:10

Columbo


#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.

like image 42
Denis Blank Avatar answered Oct 02 '22 16:10

Denis Blank