24.6 Class Specialization

I l @ ve RuBoard

You can think of a class template such as this:

 template <typename kind>stack { ... 

as instructions that tell C++ how to generate a set of classes named stack<int>, stack<double> , stack<float> , and so on. C++ will also generate automatically the member functions: stack<int>::push , stack<double>::push, and stack<float>::push .

However, if you explicitly declare a member function yourself, C++ will use your definition before generating its own. Suppose we want to have a stack store C-style strings ( char * ). We don't want to store the pointers; we want to store the actual strings. To do this, we need a special version of the push function that duplicates the string before pushing it onto the stack:

 inline void stack<char *>::push(const char *const item) {     data[count] = std::strdup(item);     ++count; } 

Note that we didn't use template<typename kind> at the beginning of the function. The template keyword tells C++, "This is a generic class. Generate specific versions from it." With no template, we are telling C++, "This is the real thing. Use it directly."

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net