Michal Špondr
Michal Špondr

Reputation: 1535

Is it possible to create a template class with later type definition?

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

Answers (3)

grzkv
grzkv

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

R Sahu
R Sahu

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

Ben Voigt
Ben Voigt

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

Related Questions