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?