[英]How to implement function(f)(x)(y, z)(g)(r) in C++?
I have been trying to implement the following function: 我一直在尝试实现以下功能:
MonsterFunction(f)(x)(y,z)(g)(r);
Where f
is a function that accepts three parameters. 其中
f
是一个接受三个参数的函数。 x, y, z
are the parameters which are passed to the function f
and all of that is passed to the function g
and the parameter r
is also passed to the function g
and the final result is returned. x, y, z
是传递给函数f
的参数,所有这些参数都传递给函数g
,参数r
也传递给函数g
并返回最终结果。
I have successfully implemented MonsterFunction(f)(x)(y,z)
, but I just can not figure out how to implement the above function. 我已成功实现了
MonsterFunction(f)(x)(y,z)
,但我无法弄清楚如何实现上述功能。
Here is the code for what I have already accomplished: 这是我已经完成的代码:
std::function<std::function<int(int, int)>(int)> MonsterFunction(std::function<int(int, int, int)> f){
return [f](int x1){
return[f, x1](int y1, int z1){
return f(x1, y1, z1);
};
};
}
Keep in mind that I only want to accomplish this with std::function
and lambda-closure functions
. 请记住,我只想用
std::function
和lambda-closure functions
来实现这一点。
I've actually did it, after a little break I was able to implement it. 我实际上已经做到了,经过一段时间的休息,我能够实现它。 It is easy as long as you track the nesting carefully.
只要您仔细跟踪嵌套,这很容易。 Here is my final code:
这是我的最终代码:
std::function<std::function<std::function<std::function<int(int)>(int(int, int))>(int, int)>(int)> MonsterFunction(std::function<int(int, int, int)> f){
return [f](int x1){
return[f, x1](int y1, int z1){
int result = f(x1, y1, z1);
return [result](int g(int, int)){
return[result,g](int r){
return g(result, r);
};
};
};
};
}
Now I am able to do calls like this MonsterFunction(Sum)(5)(5,4)(Multiply)(4)
. 现在我能够进行类似
MonsterFunction(Sum)(5)(5,4)(Multiply)(4)
调用。
Edit
编辑
As Quentin suggested, using auto
as the return type makes the function more concise: 正如Quentin所建议的,使用
auto
作为返回类型使函数更简洁:
auto MonsterFunction(std::function<int(int, int, int)> f){
return [f](int x1){
return[f, x1](int y1, int z1){
int result = f(x1, y1, z1);
return [result](int g(int, int)){
return[result,g](int r){
return g(result, r);
};
};
};
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.