C++ templates
use either keyword typename or class in "template prefix"
e.g. template <class T>
C++ templates
like "blueprints" for the compiler to use in creating class and function definition
STL
mostly template classes and functions
template definition must be in header file
so compiler can know how to define the functions
MyTemplate <T1> =! MyTemplate <T2>
there is no inheritance or any other kind of formal relationship between the two classes, because compiler defines completely different classes
An alternative to using an inheritance hierarchy
- more flexible, as template classes stand alone - more efficient than using virtual functions
An alternative to function overloading
-but code for concrete types created only as needed -compiler deduces types of user doesn't specify: int x = sizeComp ('a',7) -to specify : x=sizeComp <int,int> ('a',7.5)
Always involve one or more parameterized types
-function template to compare object sizes: template <typename T1, typename T2> int sizeComp (T1 const &o1, T2 const &o2) { return (sizeof o1 - sizeof o2); } -class template for a list that holds any type: template <typename DataType> class List {/* here refer to Data Type objects*/}
sometimes specialized for particular types
-tells compiler to use specialized version instead of creating a new definition template <> char * &greater <char *>(char *s, char*t) -No type concersions though (must be exact match), so usually better to just overload instead of specialize
even a string is actually a specialization of template, defined as follows in namespace std:
-typedef basic_string<char> string; -Also: typedef basic_sting <wchar_t>wstring;