0

I wonder what is the best practice to configure policies in policy based design. The interface of the policy is defined by its host class. Nevertheless, it is not defined how this interface needs to be implemented. Therefore, policies might need different configuration parameters. But I only want to feed one configuration (object) into the host class. The following code is a draft what I have done so far, but I am not so happy with it because it does not guarantee that there are no naming conflicts and it does not encapsulate configuration members of different policies.

class Policy1 {
  template<class Config>
  Policy1(Config cp1) {
    /* Use policy1 config members */
  }
};

class Policy2 {
  template<class Config>
  Policy2(Config cp2) {
    /* Use policy2 config members */
  }
};

template <class P1, class P2>
class Host {

  template<class Config>
  Host(Config c) : p1(P1(c)), p2(P2(c)) {...}

  P1 p1;
  P2 p2;
};

struct Config {
  int configParam1; /* Used by policy 1  */
  int configParam2; /* Used by policy 2  but might also
                       be called configParam1
                     */
}

int main() {
  Host<Policy1, Policy2> h(Config());
  return 0;
}

How can I prevent name conflicts in the configuration objects? Is there some mechanism similar to namespaces? Or does somehow has a better idea to configure my policies?

erikzenker
  • 752
  • 5
  • 18
  • 1
    I'm not familiar with this approach to Policy based design, Usually the policies are inherited, since they often carry no members and can be subjected to the empty class optimization. – StoryTeller - Unslander Monica Nov 22 '15 at 17:11
  • In general, policy-based design does not require inheritance. Adding the policy as a member works just as well. – erikzenker Nov 22 '15 at 17:20
  • 1
    Yes, They are indeed logically equivalent. But I think the empty class optimization gives inheritance a slight edge. Still, back to your question. I'm not sure I get your concern, can you expand your example and elaborate? When will a conflict occur? – StoryTeller - Unslander Monica Nov 22 '15 at 17:27
  • Two policies might use config paramters where it makes sense to give them the same variable name. But you need to give them different names to distinguish (C style). C++ solves this usually by namespaces, but this is not allowed within classes. – erikzenker Nov 22 '15 at 18:55
  • If I understand you right `Config` has 2 attributes with the same meaning but with different values because it's used by different policy classes? So why not using just one attribute and passing two different objects of class `Config` to your policy classes instead? – tomse Nov 22 '15 at 19:09
  • Using a single configuration for each policy would be an solution. Thus, each policy could declare a Config type, which the user has to provide. I was just wondering if someone has a good idea to do it with a single Config type/object. – erikzenker Nov 24 '15 at 10:02

0 Answers0