1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
Although the em(construction) of template classes will only be constructed in
chapter ref(TEMPCLASS), template classes have already extensively been
em(used) earlier. For example, abstract containers (covered in chapter
ref(Containers)) are actually defined as template classes. Like
hi(concrete class)
concrete classes (i.e., non-template classes), template classes can
participate in the construction of
i(class hierarchies).
In section ref(DERIVEDTEMPCLASS) it is shown how a i(template class) can
be derived from another template class.
As template class derivation remains to be covered, the following
discussion is necessarily somewhat abstract. Optionally, the reader may of
course skip briefly to section ref(DERIVEDTEMPCLASS), to read this
section thereafter.
In this section it should now be assumed, for the sake of argument, that a
template class tt(Vector) has somehow been derived from a tt(std::vector).
Furthermore, assume that the following template function has been
constructed to sort a vector using some function object tt(obj):
verb(
template <typename Type, typename Object>
void sortVector(std::vector<Type> vect, Object const &obj)
{
sort(vect.begin(), vect.end(), obj);
}
)
To sort tt(std::vector<string>) objects case-insensitively, the tt(class
Caseless) could be constructed as follows:
verb(
class CaseLess
{
public:
bool operator()(std::string const &before,
std::string const &after) const
{
return strcasecmp(before.c_str(), after.c_str()) < 0;
}
};
)
Now various vectors may be sorted, using tt(sortVector()):
verb(
int main()
{
std::vector<string> vs;
std::vector<int> vi;
sortVector(vs, CaseLess());
sortVector(vi, less<int>());
}
)
Applying the transformation
hi(transformation to a base class)
hi(template class: transformation to a base class)
em(transformation to a base class instantiated from a class template), the
template function tt(sortVectors()) may now also be used to sort tt(Vector)
objects. For example:
verb(
int main()
{
Vector<string> vs; // note: not `std::vector'
Vector<int> vi;
sortVector(vs, CaseLess());
sortVector(vi, less<int>());
}
)
In this example, tt(Vector)s were passed as argument to
tt(sortVector()). Applying the transformation to a base class instantiated
from a class template, the compiler will consider tt(Vector) to be a
tt(std::vector), and is thus able to deduce the template's type parameter. A
tt(std::string) for the tt(Vector vs), an tt(int) for tt(Vector vi).
Please realize the purpose of the various template parameter type deduction
transformations. They do not aim at matching function arguments to function
parameters, but having matched arguments to parameters, the transformations
may be applied to determine the actual types of the various template type
parameters.
|