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