简体   繁体   中英

C++ Policy design with dependencies

This is a followup to this question.

Basically I want a container that stores objects and later does something with them. I want to put both, the action performed on the objects ( ActionPolicy ), and the storage ( StoragePolicy ), into policy classes. At the end, there should be two functions on the class:

  • addObject() with a signature depending on ActionPolicy , ie this function should be defined in there.
  • execute() , which goes over all of the objects stored by StoragePolicy and executes ActionPolicy::evaluate(obj) on all of them.

In (partially pseudo-)code (the places marked with Here are the ones that don't work in this design):

struct ActionPolicy {
  // Signature is dependant on this policy
  void addObject(T obj, /* ... */) {
    // Do something with the object
    StoragePolicy::store(obj); // <--- Here
  }

  void eval(T obj) {
    // Do something with the object
  }
};

struct StoragePolicySingle {
  T obj;

  void store(T obj) {
    this->obj = obj;
  }

  void execute() {
    ActionPolicy::execute(obj); // <--- Here
  }
};


struct StoragePolicyMulti {
  std::vector<T> vec;

  void store(T obj) {
    vec.push_back(obj´);
  }

  void execute() {
    for (obj in vec) {
      ActionPolicy::execute(obj); // <--- Here
    }
  }
};

template <class A, class B> MyClass : public A, public B {
  // ...
};

All of this is performance-critical, so I can't just use a vector with one entry instead of StoragePolicySingle .

How would you solve this? Any pattern I'm missing?

Why does ActionPolicy need to know about StoragePolicy ?

Why does an ActionPolicy have objects added to it?

If you pass the ActionPolicy to the StoragePolicy as an argument to execute , then call eval on either the single item or the collection, does this not solve it for you?

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