Reputation: 63
I have the same class with different template type instantiation. Is it possible to point from one to another?
For example, compiling the following code
template <typename T>
class Base {
public:
Base *p;
};
int main() {
Base<int> a1;
Base<float> a2;
a1.p = &a2;
return 0;
}
returns with
error: cannot convert ‘A<float>*’ to ‘Base<int>*’ in assignment
a1.p = &a2;
Thanks!
Upvotes: 0
Views: 371
Reputation: 11340
I have the same class with different template type instantiation.
Actually no, because a template is no class, but describes a family of classes. For more detailed information see the documentation
Base<int>
and Base<float>
are two different classes, even if they come from the same template, so the compiler is right in your example. You can't have a pointer that can point to both (except for void*
which is not recommended).
Anothe possible solution as proposed by IInspectable would be std::variant of that can point to one or the the other like:
std::variant<Base<int> *, Base<float> *> ptr;
(or preferable with smart pointers instead of raw pointers)
Upvotes: 3