簡體   English   中英

C ++中的運算符組合

[英]Operator composition in c++

我想知道是否有一個優雅的解決方案來構成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(g,2.0)來應用A^2(f,2.0) A(g,2.0) 在上面的示例中,這將返回h(x)*h(x)*f(x) = x*x*x*x*exp(x)

我將如何推廣為反復應用的運營商A N次? 我真的很喜歡這里發布的答案,但是在這里並不能很好地解決。 我嘗試做嵌套的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;
}

根據我對您提出的問題的理解,您實際上是在嘗試定義

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)

使用模板專門化嘗試一下

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

因此,您希望能夠倍增功能。 好吧,聽起來不錯。 為什么我們不在的時候不+-/

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 Fun。

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

這些是支持*=類的東西。 alg_funalg_fun鍵入的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

現場例子

這是一種更有效的戰俘,無需類型擦除即可工作:

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

現場例子 它在alg_fun使用了一個新的函數compose

  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。

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

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

演示版

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM