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 :
Something along these lines, perhaps (untested):
template
class Composer {
int n_;
F f_;
public:
Composer(int n, F f) : n_(n), f_(f) {}
template
T operator()(T x) const {
int n = n_;
while (n--) {
x = f_(x);
}
return x;
}
};
template
Composer compose(F f) {
return Composer(N, f);
}
EDIT: And for the second case (tested this time):
#include
template
class Composer2 {
F0 f0_;
Composer2 tail_;
public:
Composer2(F0 f0, F... f) : f0_(f0), tail_(f...) {}
template
T operator() (const T& x) const {
return f0_(tail_(x));
}
};
template
class Composer2 {
F f_;
public:
Composer2(F f) : f_(f) {}
template
T operator() (const T& x) const {
return f_(x);
}
};
template
Composer2 compose2(F... f) {
return Composer2(f...);
}
int f(int x) { return x + 1; }
int g(int x) { return x * 2; }
int h(int x) { return x - 1; }
int main() {
std::cout << compose2(f, g, h)(42);
return 0;
}