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 :
Compose a function on itself a variable number of times. Mathematically, for a certain function F, F^n(x) = (F^{n-1} o F)(x) = F^{n-1}(F(x)).
Compose different functions together. For example, for some functions f,g,h,i,j and k of the same type, I'll have f(g(h(i(j(k(x)))))).
In my case, I'm using the following definition of F :
const std::vector<uint8_t> F(const std::vector<uint8_t> &x);
I would like to compose this function on itself n times. I have implemented the composition in a simple recursive way which is working fine :
const std::vector<uint8_t> compose(const uint8_t n, const std::vector<uint8_t> &x)
{
if(n > 1)
return compose(n-1, F(x));
return F(x);
}
For this case, is there a more efficient way an proper way to implement this composition using c++11 but without using BOOST ? It would be great to use this form if it is possible of course :
answer = compose<4>(F)(x); // Same as 'answer = F^4(x) = F(F(F(F(x))))'
For the second case, I would like to implement the composition of a variable number of functions. For a given set of functions F0, F1, ..., Fn having the same definition as F, is there an efficient and proper way to compose them where n is variable ? I think variadic template would be useful here, but I don't know how to use them in that case.
Thanks for your help.
A very general example (
g++ -std=c++1y composition.cpp
):Library part:
The whole program:
You haven't shown the body of
F
, but if you can modify it so that it mutates the input to form the output then change the signature to:Thereafter you can implement Fn as:
The compiler will unroll the loop for you if it is more efficient, but even if it doesn't an increment/compare of a local variable will be orders of magnitude faster than calling F.
You can then explcitly copy-construct new vectors when you actually want to make a copy:
Something along these lines, perhaps (untested):
EDIT: And for the second case (tested this time):
Thanks for the fun question, Gabriel of year 2013. Here is a solution. It works in c++14.
You can define
or
to reuse this code for all sorts of things.
A quick implementation of function iteration with argument forwarding. The helper type is unfortunately necessary because function templates can’t be partially specialised.
Here is a simple c++14 solution (it may probably be re-written to c++11):
Possible usage:
Here is a link to the repo with a few more examples: https://github.com/nestoroprysk/FunctionComposition