Using friends with base classes for Boost Parameter

181 views Asked by At

I'm using the Boost Parameter tutorial to create a named-parameter constructor for a playing card generator. The tutorial says to put the ArgumentPack into a base class, but I want to modify variables in the card generator class. I've thought about doing this:

class CGconstructor_base {
public:
      template<class ArgumentPack>
      CGconstructor_base(ArgumentPack const& args);/*tutorial says to put code
      in this function */
      friend CardGenerator;//so it can modify the variables of CardGenerator
}
class CardGenerator:public CGconstructor_base;

Is this legal or is there a better way to manipulate the private variables in CardGenerator and use Boost Parameter library? OS: Windows XP Pro, Compilier: Visual C++ 2008 Express,Boost: 1.39.0

1

There are 1 answers

1
Matthieu M. On BEST ANSWER

I think we need some cleanup.

  1. the friend declaration seems ill-placed, from the comment you want CGconstructor_base to be able to access CardGenerator attributes: if this is so, then the friend declaration goes into CardGenerator (I say who I consider as my friends, you do not declare yourself as being someone I consider a friend).

  2. Why do you need friend anyway ? It would be much better if as in the tutorial you used a structure and then stuffed the attributes into CGconstructor_base. This way you will be able to access them from CardGenerator naturally without this supplementary line. When you can do without the 'friend' keyword you should (usual caveat: if doing so does not increase the cost too much).

  3. you want PRIVATE inheritance here, this is a detail implementation. Only use public inheritance (or protected even) when OTHER classes/methods will need to know use you 'as-a' base.

In a nutshell:

struct CGconstructor_base {
      template<class ArgumentPack>
      CGconstructor_base(ArgumentPack const& args);/*tutorial says to put code
      in this function */

      cg_type1 cg_attr1;
      cg_type2 cg_attr2;
}; // don't forget this

class CardGenerator:private CGconstructor_base {};

I do wonder why 'inheritance' has been chosen by boost instead of (I think) cleaner composition. It is so much easier to abuse inheritance (and require Multiple-Inheritance)... I suppose it is worth a subject of its own though.