简体   繁体   中英

Composite pattern of std::functions

I am trying to implement a composite pattern for std::functions with use of template classes, where each composite class processes the return values of its children.
So the pattern classes might look something like this:

class AbstractClass {
  public:
     virtual void process() = 0;
};

template<typename ReturnType>
class PrimitiveClass : public AbstractClass {
  public: 
    ReturnType process() {
       // please note, that the result is not returned by the return statement
       return this->func();  //this is just for simplicity
    }

  private:
    std::function<ReturnType()> func;
}

template<typename ReturnType, typename ...Args>
class CompositeClass : public AbstractClass {
  public:
    ReturnType process() {
      // --> This is where I want to process all children first and then pass their return values to this->func
      // the following code is kind of a pseudo code:
      for(auto it = vector.begin(); it != vector.end(); ++it {
          results.add((**it).process())
      }
      return this->func(results)
    }

  private:
    std::function<ReturnType(Args...)> func;
    std::vector<std::shared_ptr<AbstractClass>> children;
};

So for example, I have a CompositeClass with a std::function<int(int, double, bool) and the argument types of that function are also the ReturnType s of its children. And I want to pass the return values of the children to above-mentioned std::function
Can anyone think of a way, how I can achieve this?

If I understand what you want (and if I'm not wrong)...

(1) to solve the problem of the no-covariant returned value from process() (see comment from Igor Tandetnik) you need a template abstract class to express the correct return value; by example

template <typename T>
struct abstClass 
 { virtual T process() const = 0; };

(2) so your CompositeClass (renamed nodeClass , in my following example) inherit from abstClass<ReturnType>

(3) your PrimitiveClass is useless because you can manage the case (reference to a function without arguments) as a CompositeClass with zero Args

(4) you need a leafClass to handle basic values

(5) in CompositeClass ( nodeClass ), children , instead of a std::vector of shared_ptr<AbstractClass> (that can't do what do you want), can be a

std::tuple<std::shared_ptr<abstClass<Args>>...>  children;

Given these points, I propose the following solution (that, unfortunately, is C++14 because use std::index_sequence and std::make_index_sequence that are available starting from C++14; but if you need a C++11 solution, isn't difficult write substitutes for they)

#include <tuple>
#include <memory>
#include <iostream>
#include <functional>

template <typename T>
struct abstClass 
 { virtual T process() const = 0; };

template <typename T>
class leafClass : public abstClass<T>
 {
   private:
      T  value;

   public:
      leafClass (T && v0) : value { std::forward<T>(v0) }
       { }

      T process () const
       { return value; };
 };

template <typename RetT, typename ... ArgTs>
class nodeClass : public abstClass<RetT>
 {
   private:
      using funcT = std::function<RetT(ArgTs...)>;

      template <typename T>
      using shrPAC = std::shared_ptr<abstClass<T>>;

      funcT                         func;
      std::tuple<shrPAC<ArgTs>...>  childrens;

      template <std::size_t ... Is>
      RetT processH (std::index_sequence<Is...> const &) const
       { return func(std::get<Is>(childrens)->process()...); }

   public:
      nodeClass (funcT && f0, shrPAC<ArgTs> && ... as)
         : func { std::forward<funcT>(f0) },
           childrens { std::forward<shrPAC<ArgTs>>(as)... }
       { }

      RetT process () const
       { return processH(std::make_index_sequence<sizeof...(ArgTs)>{}); }
 };

int main ()
 {
   auto func0 = [](int i, double d, bool b) { return int( b ? i+d : i-d ); };

   auto shpLci = std::make_shared<leafClass<int>>(1);
   auto shpLcd = std::make_shared<leafClass<double>>(2.2);

   auto shpNb  = std::make_shared<nodeClass<bool>>([](){ return true; });

   auto shpNc0 = std::make_shared<nodeClass<int, int, double, bool>>
      (func0, shpLci, shpLcd, shpNb);
   auto shpNc1 = std::make_shared<nodeClass<int, int, double, bool>>
      (func0, shpNc0, shpLcd, shpNb);
   auto shpNc2 = std::make_shared<nodeClass<int, int, double, bool>>
      (func0, shpNc1, shpLcd, shpNb);

   std::cout << shpNc0->process() << std::endl; // print 3
   std::cout << shpNc1->process() << std::endl; // print 5
   std::cout << shpNc2->process() << std::endl; // print 7
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM