Suppose I have a template class such as:
template <class type, size>
class myTemplate
and I had an abstract base class:
class myDataType
and various derived classes
class subDataType1 : public myDataType
class subDataType2 : public myDataType
...
class subDataTypeN : public myDataType
What I WANT to do, is call:
myTemplate<myDataType, size> myObject;
However, this obviously doesn't work, because inside the template, I would be instantiating an object of an abstract class. Basically, I want the template to work with either of my derived classes, but I don't know how to mechanize this (coming from Java where "solutions" or workarounds such as type wildcards and "Object", for example, may have allowed me to at least get past the compiler's checks).
What I really want, is without altering my template class, allow multiple data types without instantiating multiple objects of my template class.
I should mention that I'm aware that the solution to this likely involves a call such as:
myTemplate<myDataType*, size> myObject
But I'll likely need more details than that, as I'm new to C++ (I don't know what I don't know).
Coming from Java you need to understand that templates in C++ are not like generics in Java, more precisely templates are compile-time generics.
Everything that has something to do with a template or is a template exists only at compile-time as such when you do things like myTemplate<myDataType, size> myObject;
there are actually two things that happen:
1.At compile-time when myDataType
and size
are substituted to the template, which in turn is instantiated to create a type. This type's name is myTemplate<myDataType*, size>
and is the only this is the type with which you work at run-time.
2.At run-time the created type (myTemplate) is instantiated in order to create an object of that type.
What we can note from this is that a template instantiated with different template arguments will produce totally different types available at run-time which will not have any relationship between them, the relationship existing only at compile time. This is in contrast to how generics work in java where the generic argument is casted to Object at compile time and later, at run-time is casted to the actual type.
Hope this helped shed some light on C++ templates.