C ++中的运算符组合

时间:2018-10-05 16:44:53

标签: c++ c++11 functional-programming

我想知道是否有一个优雅的解决方案来构成C ++中的数学运算符。按运算符,我的意思是这样的:

template<class H>
class ApplyOp {
    H h;
public:
    ApplyOp(){}
    ApplyOp(H h_i) : h(h_i) {}

    template<class argtype>
    double operator()(argtype f,double x){
        return h(x)*f(x);
    }
};

上面的类使用“帮助器功能” h(x)。例如,

struct Helper{
    Helper(){}
    double operator()(double x){return x*x;}
};

struct F{
    F(){}
    double operator()(double x){return exp(x);}
};

int main()
{
    Helper h;
    F f;
    ApplyOp<Helper> A(h);

    std::cout<<"A(f,2.0) = "<<A(f,2.0)<<std::endl; //Returns 2^2*exp(2) = 29.5562...

    return 0;
}

现在,我想对运算符进行两次或多次运算,即计算A^2(f,2.0)。在上面的示例中,这将返回h(x)*h(x)*f(x)。请注意,这不是 函数组成,即我不想计算A(A(f,2.0),2.0)。而是考虑矩阵的计算能力:如果是h(x) = M(矩阵),我想要M*M*...*M*x

我能够使用std::bind()达到A^2的期望结果(但没有更高的幂!),如下所示:

auto g = std::bind(&ApplyOp<Helper>::operator()<F>,&A,f,std::placeholders::_1);

对于生成的g,我可以通过简单地调用A^2(f,2.0)来应用A(g,2.0)。在上述示例中,这将返回h(x)*h(x)*f(x) = x*x*x*x*exp(x)

我如何将其概括为迭代地将操作符A应用N次?我真的很喜欢发布here的答案,但是在这里并不能完全解决问题。我尝试做嵌套的std:bind,但是很快就遇到了严重的编译器错误。

有什么想法吗?

完整的工作示例:

#include<iostream>
#include<math.h>
#include<functional> //For std::bind

template<class H>
class ApplyOp {
    H h;
public:
    ApplyOp(){}
    ApplyOp(H h_i) : h(h_i) {}

    template<class argtype>
    double operator()(argtype f,double x){
        return h(x)*f(x);
    }
};

struct Helper{
    Helper(){}
    double operator()(double x){return x*x;}
};

struct F{
    F(){}
    double operator()(double x){return exp(x);}
};

int main()
{
    Helper h;
    F f;
    ApplyOp<Helper> A(h);

    std::cout<<"A(f,2.0) = "<<A(f,2.0)<<std::endl; //Returns 2^2*exp(2) = 29.5562...

    auto g = std::bind(&ApplyOp<Helper>::operator()<F>,&A,f,std::placeholders::_1);

    std::cout<<"A^2(f,2.0) = "<<A(g,2.0) <<std::endl; //Returns 2^4*exp(2) = 118.225... 

    return 0;
}

4 个答案:

答案 0 :(得分:1)

根据我从您的问题中可以理解的内容,您实际上是在尝试定义

A^1(h, f, x) = h(x) * f(x)
A^n(h, f, x) = h(x) * A^(n-1)(h, f, x)

如果您愿意使用C ++ 17,请可以在此基础上构建

#include <iostream>
#include <math.h>

template <int N>
struct apply_n_helper {
  template <typename H, typename F>
  auto operator()(H h, F f, double x) const {
    if constexpr(N == 0) {
      return f(x);
    } else {
      return h(x) * apply_n_helper<N - 1>()(h, f, x);
    }
  }
};

template <int N>
constexpr auto apply_n = apply_n_helper<N>();

int main() {
  auto sqr = [](double x) { return x * x; };
  auto exp_ = [](double x) { return exp(x); };

  std::cout << apply_n<100>(sqr, exp_, 2.0) << '\n';
  std::cout << apply_n<200>(sqr, exp_, 2.0) << '\n';
  return 0;
}

如果不能使用C ++ 17,则可以轻松地重写它以使用模板专业化功能来代替constexpr-if。我将把它保留为练习。这是此代码的编译器资源管理器链接:https://godbolt.org/z/5ZMw-W

编辑回头看这个问题,我发现您实质上是在尝试计算(h(x))^n * f(x)的方式,这样您就不必在运行时实际执行任何循环,并且生成的代码等效于:

auto y = h(x);
auto result = y * y * ... * y * f(x)
              \_____________/
                  n times
return result;

实现此目标的另一种方法是进行如下操作

#include <cmath>
#include <iostream>

template <size_t N, typename T>
T pow(const T& x) {
    if constexpr(N == 0) {
        return 1;
    } else if (N == 1) {
        return x;
    } else {
        return pow<N/2>(x) * pow<N - N/2>(x);
    }
}

template <int N>
struct apply_n_helper {
    template <typename H, typename F>
    auto operator()(H h, F f, double x) const {
        auto tmp = pow<N>(h(x));
        return tmp * f(x);
    }
};

template <int N>
constexpr auto apply_n = apply_n_helper<N>();

int main()
{
    auto sqr = [](double x) { return x * x; };
    auto exp_ = [](double x) { return exp(x); };

    std::cout << apply_n<100>(sqr, exp_, 2.0) << '\n';
    std::cout << apply_n<200>(sqr, exp_, 2.0) << '\n';
    return 0;
}

在这里,pow函数的使用使我们免于多次评估h(x)

答案 1 :(得分:1)

尝试使用模板专门化功能

#include<iostream>
#include<math.h>
#include<functional> //For std::bind

template<class H>
class ApplyOp {
    H h;
public:
    ApplyOp(){}
    ApplyOp(H h_i) : h(h_i) {}

    template<class argtype>
    double operator()(argtype f,double x){
        return h(x)*f(x);
    }
};

struct Helper{
    Helper(){}
    double operator()(double x){return x*x;}
};

struct F{
    F(){}
    double operator()(double x){return exp(x);}
};

// C++ doesn't permit recursive "partial specialization" in function
// So, make it a struct instead
template<typename T, typename U, typename W, int i>
struct Binder {
    auto binder(U b, W c) {
        // Recursively call it with subtracting i by one
        return [&](T x){ return b(Binder<T, U, W, i-1>().binder(b, c), x); };
    }
};

// Specialize this "struct", when i = 2
template<typename T, typename U, typename W>
struct Binder<T, U, W, 2> {
    auto binder(U b, W c) {
        return [&](T x){ return b(c, x); };
    }
};

// Helper function to call this struct (this is our goal, function template not
// struct)
template<int i, typename T, typename U, typename W>
auto binder(U b, W d) {
    return Binder<T, U, W, i>().binder(b, d);
}

int main()
{
    Helper h;
    F f;
    ApplyOp<Helper> A(h);

    std::cout<<"A(f,2.0) = "<<A(f,2.0)<<std::endl; //Returns 2^2*exp(2) = 29.5562...

    // We don't need to give all the template parameters, C++ will infer the rest
    auto g = binder<2, double>(A, f);

    std::cout<<"A^2(f,2.0) = "<<A(g,2.0) <<std::endl; //Returns 2^4*exp(2) = 118.225... 

    auto g1 = binder<3, double>(A, f);

    std::cout<<"A^3(f,2.0) = "<<A(g1,2.0) <<std::endl; //Returns 2^6*exp(2) = 472.2

    auto g2 = binder<4, double>(A, f);

    std::cout<<"A^4(f,2.0) = "<<A(g2,2.0) <<std::endl; //Returns 2^8*exp(2) = 1891.598... 

    return 0;
}

答案 2 :(得分:0)

因此,您希望能够乘法功能。好吧,听起来不错。为什么我们不在的时候+-/呢?

template<class F>
struct alg_fun;

template<class F>
alg_fun<F> make_alg_fun( F f );

template<class F>
struct alg_fun:F {
  alg_fun(F f):F(std::move(f)){}
  alg_fun(alg_fun const&)=default;
  alg_fun(alg_fun &&)=default;
  alg_fun& operator=(alg_fun const&)=default;
  alg_fun& operator=(alg_fun &&)=default;

  template<class G, class Op>
  friend auto bin_op( alg_fun<F> f, alg_fun<G> g, Op op ) {
    return make_alg_fun(
      [f=std::move(f), g=std::move(g), op=std::move(op)](auto&&...args){
        return op( f(decltype(args)(args)...), g(decltype(args)(args)...) );
      }
    );
  }

  template<class G>
  friend auto operator+( alg_fun<F> f, alg_fun<G> g ) {
    return bin_op( std::move(f), std::move(g), std::plus<>{} );
  }
  template<class G>
  friend auto operator-( alg_fun<F> f, alg_fun<G> g ) {
    return bin_op( std::move(f), std::move(g), std::minus<>{} );
  }
  template<class G>
  friend auto operator*( alg_fun<F> f, alg_fun<G> g ) {
    return bin_op( std::move(f), std::move(g),
      std::multiplies<>{} );
  }
  template<class G>
  friend auto operator/( alg_fun<F> f, alg_fun<G> g ) {
    return bin_op( std::move(f), std::move(g),
      std::divides<>{} );
  }

  template<class Rhs,
    std::enable_if_t< std::is_convertible<alg_fun<Rhs>, F>{}, bool> = true
  >
  alg_fun( alg_fun<Rhs> rhs ):
    F(std::move(rhs))
  {}

  // often doesn't compile:
  template<class G>
  alg_fun& operator-=( alg_fun<G> rhs )& {
    *this = std::move(*this)-std::move(rhs);
    return *this;
  }
  template<class G>
  alg_fun& operator+=( alg_fun<G> rhs )& {
    *this = std::move(*this)+std::move(rhs);
    return *this;
  }
  template<class G>
  alg_fun& operator*=( alg_fun<G> rhs )& {
    *this = std::move(*this)*std::move(rhs);
    return *this;
  }
  template<class G>
  alg_fun& operator/=( alg_fun<G> rhs )& {
    *this = std::move(*this)/std::move(rhs);
    return *this;
  }
};
template<class F>
alg_fun<F> make_alg_fun( F f ) { return {std::move(f)}; }

auto identity = make_alg_fun([](auto&& x){ return decltype(x)(x); });
template<class X>
auto always_return( X&& x ) {
  return make_alg_fun([x=std::forward<X>(x)](auto&&... /* ignored */) {
    return x;
  });
}

我认为是这样。

auto square = identity*identity;

我们还可以使用类型删除的Alg乐趣。

template<class Out, class...In>
using alg_map = alg_fun< std::function<Out(In...)> >;

这些是支持*=之类的东西。 alg_fun通常输入的擦除字数不够。

template<class Out, class... In>
alg_map<Out, In...> pow( alg_map<Out, In...> f, std::size_t n ) {
  if (n==0) return always_return(Out(1));
  auto r = f;
  for (std::size_t i = 1; i < n; ++i) {
    r *= f;
  }
  return r;
}

可以更有效地完成工作。

测试代码:

auto add_3 = make_alg_fun( [](auto&& x){ return x+3; } );
std::cout << (square * add_3)(3)  << "\n";; // Prints 54, aka 3*3 * (3+3)

alg_map<int, int> f = identity;
std::cout << pow(f, 10)(2) << "\n"; // prints 1024

Live example

这是一种更有效的战俘,无需类型擦除即可工作:

inline auto raise(std::size_t n) {
  return make_alg_fun([n](auto&&x)
    -> std::decay_t<decltype(x)>
  {
    std::decay_t<decltype(x)> r = 1;
    auto tmp = decltype(x)(x);

    std::size_t bit = 0;
    auto mask = n;
    while(mask) {
      if ( mask & (1<<bit))
        r *= tmp;
      mask = mask & ~(1<<bit);
      tmp *= tmp;
      ++bit;
    }
    return r;
  });
}
template<class F>
auto pow( alg_fun<F> f, std::size_t n ) {
  return compose( raise(n), std::move(f) );
}

Live example。它在compose中使用了一个新函数alg_fun

  template<class G>
  friend auto compose( alg_fun lhs, alg_fun<G> rhs ) {
    return make_alg_fun( [lhs=std::move(lhs), rhs=std::move(rhs)](auto&&...args){
        return lhs(rhs(decltype(args)(args)...));
    });
  }

哪个compose(f,g)(x) := f(g(x))

您的代码现在变成了

alg_fun<Helper> h;
alg_fun<F> f;

auto result = pow( h, 10 )*f;

h(x)*h(x)*h(x)*h(x)*h(x)*h(x)*h(x)*h(x)*h(x)*h(x)*f(x)。除了(使用有效版本),我只调用一次h,并将结果提高到10的幂。

答案 3 :(得分:0)

我的意思是您可以使用其他课程:

template <typename T, std::size_t N>
struct Pow
{
    Pow(T t) : t(t) {}

    double operator()(double x) const
    {
        double res = 1.;

        for (int i = 0; i != N; ++i) {
            res *= t(x);
        }
        return res;
    }

    T t;  
};

并使用

ApplyOp<Pow<Helper, 2>> B(h);而不是ApplyOp<Helper> A(h);

Demo

相关问题