er344tre
er344tre

Reputation: 105

C++ executing function and lambda inside

I am trying to run similar code to this python code in c++.

def f1(a):
    def f2(b):
        return a*b

    return f2
#
if __name__== '__main__':
    x=f1(3)(4)
    print('Result = {0}'.format(x))

Output : Result = 12

In C++,

#include<iostream>
#include<vector>
#include <functional>

int f1(int &x)
//should I return lambda from function ? std::function<decltype (...) f1? 
{
    return [x](int &y) ->int
    {return x * y;} ;

}

int main()
{
  int y = { 3 }, z = { 4 };
    int x=f1(y)(z);
    std::cout<<x<<"\n";
    return 0;
}

But I do not know the correct way of doing it. Can someone comment?

Upvotes: 1

Views: 79

Answers (2)

Nicolas Tisserand
Nicolas Tisserand

Reputation: 488

This is how it would look if you want to pass both values to f1:

#include <iostream>
#include <vector>
#include <functional>

std::function<int ()> f1 (int& x, int& y)
{
    return [x, y] () -> int {
        return x * y;
    };
}

int main ()
{
    int y = { 3 }, z = { 4 };
    int x = f1(y, z)();
    std::cout << x << "\n";
    return 0;
}

In that case, the returned function will not take any parameters when called, since both values have already been captured inside the lambda.

Upvotes: 0

Nicolas Tisserand
Nicolas Tisserand

Reputation: 488

Try this, perhaps?

#include <iostream>
#include <vector>
#include <functional>

std::function<int (int&)> f1 (int& x)
{
    return [x] (int& y) -> int {
        return x * y;
    };
}

int main ()
{
    int y = { 3 }, z = { 4 };
    int x = f1(y)(z);
    std::cout << x << "\n";
    return 0;
}

Since f1 is a higher-order function, you need to make it return a function. std::function wraps anything that can be called as a function with the signature specified in its template parameter into a value that can be passed around, so that's a good candidate for the return type.

Upvotes: 1

Related Questions