I am currently coding some cryptographic algorithms in C++11 that require a lot of function compositions. There are 2 types of composition I have to deal with :
A quick implementation of function iteration with argument forwarding. The helper type is unfortunately necessary because function templates can’t be partially specialised.
#include
#include
using namespace std;
template
struct iterate_helper {
function f;
iterate_helper(function f) : f(f) {}
A operator()(A&& x) {
return f(iterate_helper(f)(forward(x)));
};
};
template
struct iterate_helper<1, A> {
function f;
iterate_helper(function f) : f(f) {}
A operator()(A&& x) {
return f(forward(x));
};
};
template
function iterate(function f) {
return iterate_helper(f);
}
int succ(int x) {
return x + 1;
}
int main() {
auto add5 = iterate<5>(function(succ));
cout << add5(10) << '\n';
}