函数组合在C ++ / C ++ 11 [英] function composition in C++ / C++11
问题描述
我目前正在编写一些需要大量函数组合的C ++ 11中的加密算法。有两种类型的组成我必须处理:
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 :
-
在自己上构造一个函数可变次数。在数学上,对于某个函数F,F ^ n(x)=(F ^ {n-1} o F)(x)= F ^ {n-1}(F(x))。
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)).
将不同的功能组合在一起。例如,对于一些相同类型的函数f,g,h,i,j和k,我将有f(g(h(i(j(k(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)))))).
在我的例子中,我使用以下F的定义:
In my case, I'm using the following definition of F :
const std::vector<uint8_t> F(const std::vector<uint8_t> &x);
我想自己组合这个函数n次。我已经实现了一个简单的递归方式,这是工作正常的组合:
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);
}
对于这种情况,是否有更有效的方法组合使用c ++ 11但不使用BOOST ?
当然可以使用这个表单:
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))))'
对于第二种情况,我想实现可变数量的函数的组合。对于具有与F相同定义的给定函数集合F0,F1,...,Fn,是否存在有效和适当的方法来组合它们,其中n是变量?
我认为variadic模板将在这里有用,但我不知道如何使用它们。
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.
感谢您的帮助。
推荐答案
(未测试):
template <typename F>
class Composer {
int n_;
F f_;
public:
Composer(int n, F f) : n_(n), f_(f) {}
template <typename T>
T operator()(T x) const {
int n = n_;
while (n--) {
x = f_(x);
}
return x;
}
};
template <int N, typename F>
Composer<F> compose(F f) {
return Composer<F>(N, f);
}
EDIT:这次测试):
And for the second case (tested this time):
#include <iostream>
template <typename F0, typename... F>
class Composer2 {
F0 f0_;
Composer2<F...> tail_;
public:
Composer2(F0 f0, F... f) : f0_(f0), tail_(f...) {}
template <typename T>
T operator() (const T& x) const {
return f0_(tail_(x));
}
};
template <typename F>
class Composer2<F> {
F f_;
public:
Composer2(F f) : f_(f) {}
template <typename T>
T operator() (const T& x) const {
return f_(x);
}
};
template <typename... F>
Composer2<F...> compose2(F... f) {
return Composer2<F...>(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;
}
这篇关于函数组合在C ++ / C ++ 11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!