samedi 23 septembre 2017

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 ReturnTypes 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?

Aucun commentaire:

Enregistrer un commentaire