C++执行函数和 lambda 内部

C++ executing function and lambda inside

本文关键字:lambda 内部 函数 执行 C++      更新时间:2023-10-16

我正在尝试在c ++中运行与此python代码类似的代码。

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

输出 : Result = 12

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;
}

但我不知道正确的方法。有人可以评论吗?

试试这个,也许?

#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;
}

由于f1是一个高阶函数,因此需要使其返回一个函数。 std::function 将任何可以作为函数调用的内容(其模板参数中指定的签名(包装成可以传递的值,因此这是返回类型的良好候选项。

如果要将两个值传递给 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;
}

在这种情况下,返回的函数在调用时不会接受任何参数,因为这两个值都已在 lambda 中捕获。