gpt4 book ai didi

c++ - C++/C++11 中的函数组合

转载 作者:IT老高 更新时间:2023-10-28 21:56:02 24 4
gpt4 key购买 nike

我目前正在用 C++11 编写一些需要大量函数组合的加密算法。我必须处理两种类型的组合:

  1. 在自身上多次组合一个函数。在数学上,对于某个函数 F,F^n(x) = (F^{n-1} o F)(x) = F^{n-1}(F(x))。

  2. 将不同的功能组合在一起。例如,对于某些相同类型的函数 f,g,h,i,j 和 k,我将有 f(g(h(i(j(k(x))))))。

就我而言,我使用 F 的以下定义:

const std::vector<uint8_t> F(const std::vector<uint8_t> &x);

我想自己编写这个函数 n 次。我以简单的递归方式实现了组合,效果很好:

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 来实现此组合的正确方法?当然,如果可能的话,使用这种形式会很棒:

answer = compose<4>(F)(x); // Same as 'answer = F^4(x) = F(F(F(F(x))))'

对于第二种情况,我想实现可变数量函数的组合。对于给定的一组函数 F0, F1, ..., Fn 与 F 具有相同的定义,是否有一种有效且适当的方法来组合它们,其中 n 是可变的?我认为可变参数模板在这里会很有用,但我不知道在这种情况下如何使用它们。

感谢您的帮助。

最佳答案

类似的东西,也许(未经测试):

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);
}

编辑:对于第二种情况(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++/C++11 中的函数组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19071268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com