I am trying to add two c++ lambda-funtions. What I mean by that is the following:
Assume you have two functions f
and g
with one or more arguments each, lets say f(x,y)
and g(x,y)
. I want to add both of them into a new function h like this:
h = f + g
And the evaluation should work like this:
h(x,y) = f(x,y) + g(x,y)
So far I have tried the following code, but it does not work. The "cin" at the end is just there to prevent the console from closing automatically.
#include <iostream>
#include <functional>
using namespace std;
function<int (int,int)> add(function<int(int, int)> g, function<int(int, int)> f)
{
return [&](int x, int y)->int{return g(x, y) + f(x, y); };
}
int main()
{
int i = 0;
function<int (int,int)> sum = [](int x, int y)->int { return x + y; };
function<int (int,int)> mul = [](int x, int y)->int { return x * y; };
cout << sum(1, 2) << endl;
cout << mul(3, 4) << endl;
function<int(int, int)> s = add(sum, mul);
cout << s(2, 3) << endl;
cin >> i;
}
The code compiles but it stops working when I try to evaluate s(2,3). It just says the programm stopped working and I have to close it. I am using Visual Studio 2013.
Does anyone know how to do this right? Or do you know any libraries that can do this out of the box?
Serverless applications usually consist of multiple Lambda functions. Each Lambda function can use only one runtime but you can use multiple runtimes across multiple functions. This enables you to choose the best runtime for the task of the function.
Significance of Lambda Function in C/C++ Lambda Function − Lambda are functions is an inline function that doesn't require any implementation outside the scope of the main program. Lambda Functions can also be used as a value by the variable to store.
In C++11 and later, a lambda expression—often called a lambda—is a convenient way of defining an anonymous function object (a closure) right at the location where it's invoked or passed as an argument to a function.
A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.
It's subtle.
function<int (int,int)> add(function<int(int, int)> g, function<int(int, int)> f)
{
return [&](int x, int y)->int{return g(x, y) + f(x, y); };
// ^-- This here
}
You capture g
and f
by reference, and store those references in the std::function
you return. But those are references to a function's local variables, so they dangle the second you return. Your code therefore simply has undefined behavior.
A simple fix would be to capture by value [=]
.
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