Fred Finkle
Fred Finkle

Reputation: 2017

Creating a pointer to a templated class

I know that if I use a base class, I can effectively create a pointer to a templated class. Is there an easier way?

So. Here is an example using a base class

class A {}
template <class T>
class B : public A {}

Now, I can create an instance of B<T> and point to it using the base class A. Is there an easier way? A more direct way? One that doesn't involve creating a "dummy" base class.

Upvotes: 0

Views: 206

Answers (1)

Wyzard
Wyzard

Reputation: 34563

Different instances of your template — say, B<int> and B<char> — are completely separate types, just like int and char are separate types. You can't have a single pointer that can point to either type of object unless you derive them both from the same base class, as in your example. Just like you can't have a single pointer variable that can point to either an int or a char.

But if you only want your pointer to point to a single specific type, you can just declare a pointer of type B<int> * or B<char> * or whatever. You don't need the base class A for that.

That single specific type might be specified as an argument of some other template, of course. For example, you could have a template class C<T>, which contains a pointer of type B<T> *, so a C<int> will have a B<int> * member and a C<char> will have a B<char> * member. Once again, you don't need the A base class for that.

Upvotes: 3

Related Questions