C++ 在里面执行函数和 lambda

标签 c++ c++11

我正在尝试在 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))

输出:结果 = 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 将任何可以作为函数调用的东西包装到一个可以传递的值中,并在其模板参数中指定签名,因此这是一个很好的返回类型候选者。

关于C++ 在里面执行函数和 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49702522/

相关文章:

c++ - 保护 QML 源代码免遭抄袭

c++ - 为什么要删除基类的默认复制和移动构造函数和赋值?

c++ - 克服 Visual Studio 2013 中的 decltype 问题

android - 在 android 上用 opengl 移动正方形

c++ - VSCode 在构建前不显示错误

c++ - 模板类型的 ADL 和友元函数

c++ - 在 unordered_set 中使用数组作为键

c++11 - 是否可以创建特定类的 lambda 方法?

c++ - 如何检查商是否为整数? C++

c++ - 在 C++ 中模拟 CPU 负载