Kit
Kit

Reputation: 51

Implementing a class that uses a templated class without making original class a template

Sorry if the title is confusing. Hopefully the example code will make it more clear.

Lets say I have a class:

template <typename T>
Class_A {
    //has some methods

}

Now I also have a class:

Class_B {

   vector<Class_A *> array;

   void add( Class_A * arg) {
       array.push_back(arg);
   }

}

So right now Class_B wouldn't work because I am not using like the T argument for my class_A arguments. My question is there a way to do this without making Class_B a template. Ideally the vector would be able to hold things like Class_A<int> and Class_A<string> so I really don't want Class_B templated.

Any ideas would be greatly appreciated!

Upvotes: 0

Views: 43

Answers (2)

iammilind
iammilind

Reputation: 69988

Derive from class A_Base with destructor & relevant methods as virtual. Use this A_Base, wherever you don't want templates. E.g.

template<typename T>
class Class_A : public A_Base {
   ~Class_A() override; 
  // Other virtual methods
};

Upvotes: 1

cdhowie
cdhowie

Reputation: 168988

The only way to do this without making Class_B a template would be to have the type be polymorphic; that is, have the template class Class_A inherit another class (say, Class_A_base) and store pointers to Class_A_base instead.

If you explain a bit more what you're trying to accomplish with this pattern, a better solution might be possible.

Upvotes: 0

Related Questions