I l @ ve RuBoard |
Templates go a bit further than simple code generation. They can handle special cases as well. Suppose we want to use the function max to compare C style strings as well: const char *name1 = "Able"; const char *name2 = "Baker"; std::cout << max(name1, name2) << '\n'; We have a problem, because C Style strings are represented by a character pointer ( char * ). The comparison: if (d1 > d2) compares the value of the pointers , not the data that's pointed to. What we want to do is tell C++: "Use the normal comparison except when the data type is a C style string, and then use strcmp ." This is done through a process called specialization . We declare a special version of the max function just for strings: char *max(const char *const d1, const char *const d2) { if (std::strcmp(d1, d2) > 0) return (d1); return (d2); } When C++ first sees the use of the function max , it looks through the list of simple functions before it looks through its list of templates. Thus when we have: std::cout << max(name1, name2) << '\n'; C++ will find the simple function: max(const char *const, const char *const) before trying to expand the template max(kind d1, kind d2) . Example 24-1 illustrates the use of template functions. Example 24-1. max-t/max.cpp#include <iostream> #include <cstring> // A template for the "max" function template<typename kind> kind max(kind d1, kind d2) { if (d1 > d2) return (d1); return (d2); } // A specialization for the "max" function // because we handle char * a little differently const char *const max(const char *const d1, const char *const d2) { if (std::strcmp(d1, d2) > 0) return (d1); return (d2); } int main( ) { // Let's test out max std::cout << "max(1,2) " << max(1,2) << '\n'; std::cout << "max(2,1) " << max(2,1) << '\n'; std::cout << "max(\"able\", \"baker\") " << max("able", "baker") << '\n'; std::cout << "max(\"baker\", \"able\") " << max("baker", "able") << '\n'; return (0); } |
I l @ ve RuBoard |