C++ Class inheriting from template class without k

2019-04-06 10:09发布

问题:

I am designing a template class Policy which needs to be able to handle pointers to other classes.

template <class P>
class Policy
{
  private:   
    const P *state;
  public:
    Policy (P const* s) : state(s){};
};

This works fine. Now I want to inherit from the above template class and create new subclasses:

class Greedy : public Policy<???>
{
  public:
    template <typename P> Greedy (P const* s) : Policy(s) {}:
};

class Explora : public Policy<???>
{ 
  public:
    template <typename P> Explora (P const* s) : Policy(s) {}:
};

Problem is that when defining those classes I do not know what type they will be using for the base template class. Is this even possible to do ? I want the type obtained from the inherited class constructor (probably templated), and then pass it to the base class construtor. Can I do that ? If yes, how ? typedefining enums ? I have seen this question but it doesn't in my opinion really answer the question.

回答1:

Make them template classes:

template <typename P>
class Greedy : public Policy<P>
{
    // now you know
};


回答2:

You can certainly do it (see GMan's answer for the correct parametrization of the derived type), but bear in mind that you will get entirely independent class hierarchies for every type P. You are not magically creating a super class that has an arbitrary number of member types.

Consider templates as a code generation tool. They do not create a "type-generic type", rather they create lots of parallel instances of concrete, static types at compile time following a generic pattern.


If you truly want one single common base type, perhaps you can make the type of state polymorphic:

class Policy // no template
{
  StateBase * state;
public:
  Policy(StateBase * s) : state(s) { }
};

Then all your derived classes can access the states' common interface.