Reputation: 1535
Assume this pseudocode:
Generic<unknown_type>* p;
if (type == A)
p = new Generic<AClass>;
else if (type == B)
p = new Generic<BClass>;
else
p = new Generic<CClass>;
Is it possible to create pointer to template class without type?
Upvotes: 0
Views: 76
Reputation: 2619
What you are trying to do is to determine template type during the execution time, but this denies the very nature of the templates in C++, which are designed to be determined during compilation.
Thus, what you are trying to do is not possible.
Upvotes: 1
Reputation: 206567
No. That's not possible.
Generic<AClass>
, Generic<BClass>
, and Generic<CClass>
are all different types without a common base class.
Upvotes: 0
Reputation: 283624
It is possible to declare a template class, use pointers to it, and later provide the definition. But that's not actually what your code is trying to do.
You're trying to declare and use a variable with incomplete type. That's not permitted. You could however parameterize the whole piece of code, so it too becomes a template. Then it reads more like:
Generic<TypeParam>* p = new Generic<TypeParam>;
and depending on TypeParam
, can be expanded (only at compile-time) to any of the three cases you show.
To do type selection at runtime, you'll need a common base class. Template specializations are not automatically related by inheritance in any way.
Upvotes: 2