Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transforming a two-variable std::function to a single-variable one

Tags:

c++

c++11

lambda

I have a function which gets two values, x and y, and returns the result:

std::function< double( double, double ) > mult = 
  []( double x, double y){ return x*y; };

Now I want to get a single-variable function for a constant y. I have written the following code, but it doesn't work.

std::function<
  std::function< double(double) > (
    std::function< double(double, double) >,
    double
  )
> funcYgivenX =
  [](std::function< double(double, double) > func2d, double inX) {
    return [&func2d, &inX]( double inY ) {
      return func2d(inX, inY);
    };
  };

What am I doing wrong here? And what is the best (most efficient) way to do this?

like image 858
Eliad Avatar asked Dec 09 '22 02:12

Eliad


1 Answers

In C++11, std::bind is essentially obsolete with the introduction of lambdas. Here's an example of binding using a lambda.

int add(int a, int b) {return a + b;}

int main() {
  auto add2 = [](int a){ return add(a,2); };

  std::cout << add2(3) << std::endl; // prints 5
}

For reference concerning preference of lambdas over std::bind one can read Effective Modern C++ by Scott Meyers, Item 32. In C++11 it's not possible to move capture with a lambda, and this behavior can only be emulated with std::bind. With introduction of init capture for lambdas in C++14, even that corner case can be nicely solved with lambdas.

like image 103
SU3 Avatar answered May 12 '23 14:05

SU3