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. 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.
I have successfully implemented MonsterFunction(f)(x)(y,z)
, but I just can not figure out how to implement the above function.
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
.
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)
.
Edit
As Quentin suggested, using auto
as the return type makes the function more concise:
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);
};
};
};
};
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.