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