Template Limitations

Suppose you have a template function:

template <class T>     // or template <typename T>
void f(T a, T b)
{...}

Often the code makes assumptions about what operations are possible for the type. For instance, the following statement assumes that assignment is defined, and this would not be true if type T is a built-in array type:

a = b;

Similarly, the following assumes > is defined, which is not true if T is an ordinary structure:

if (a > b)

Also the > operator is defined for array names, but because array names are addresses, it compares the addresses of the arrays, which may not be what you have in mind. And the following assumes the multiplication operator is defined for type T, which is not the case if T is an array, a pointer, or a structure:

T c = a*b;

In short, it’s easy to write a template function that cannot handle certain types. On the other hand, sometimes a generalization makes sense, even if ordinary C++ syntax doesn’t allow for it. For example, it could make sense to add structures containing position coordinates, even though the + operator isn’t defined for structures. One approach is that C++ allows one to overload the + operator so that it can be used with a particular form of structure or class. Chapter 11 discusses this facility. A template that requires using the + operator then could handle a structure that had an overloaded + operator. Another approach is to provide specialized template definitions for particular types. Let’s look at that next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.107.193