C ++ class inheriting a template class without knowing the type?

I am developing a template class policy that should handle pointers to other classes.

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

It works great. 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) {}: }; 

The problem is that when defining these classes I do not know what type they will use for the base template. Can this be done? I want to get the type obtained from the inherited class constructor (probably template), and then pass it to the construtor base class. I can do it? If so, how? typedefining enums? I saw this question , but, in my opinion, it really does not answer the question.

+8
c ++ inheritance class templates
source share
2 answers

Create template classes:

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

You can do this (see GMan's answer for correctly parameterizing the derived type), but keep in mind that you will get completely independent class hierarchies for each type P You do not magically create a superclass that has an arbitrary number of member types.

Consider templates as a code generation tool. They do not create a type of a type of type, but create many parallel instances of specific static types at compile time after a common template.


If you really need one common base type, perhaps you can make the state type polymorphic:

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

Then all your derived classes can access the common state interface.

+1
source share

All Articles