In 'The C++ Programming Language', Stroustrup states that:
"Another form of commonality can be expressed through templates (§2.7, Chapter 13). A class
template specifies a family of classes. For example, a list template specifies ‘‘list of T,’’ where
‘‘T’’ can be any type. Thus, a template is a mechanism for specifying how one type is generated
given another type as an argument. The most common templates are container classes such as lists,
arrays, and associative arrays and the fundamental algorithms using such containers. It is usually a
mistake to express parameterization of a class and its associated functions with a type using inheritance.
It is best done using templates."
I really can't understand the last sentence... What does it mean "parameterization of a class" ? It would be great if someone clears that.
Thanks.
For example, when instead of making a class List templated so that the type that its nodes hold can be defined by the user, you make it a safely derivable class that the user will have to inherit from. However there are a few, rare cases where this is what you need to do. For example:
1 2 3 4 5 6 7 8 9 10
BaseList *list;
switch (user_input()){
case INTEGER:
list=new IntegerList;
break;
case STRING:
list=new StringList;
break;
//...
}
You can't do this with templates because they rely on compile time information, and input is run time information.
You can't do this with templates because they rely on compile time information, and input is run time information.
You can, if you have a non-templated base class and a templated derived class. Of course you have to use polymorpshism too, but you don't have to write a derived class for every type.