Bruce Eckel's Thinking in C++, 2nd Ed | Contents | Prev | Next |
//: C19:Sorted.h // Template specialization #ifndef SORTED_H #define SORTED_H #include <vector> template<class T> class Sorted : public std::vector<T> { public: void sort(); }; template<class T> void Sorted<T>::sort() { // A bubble sort for(int i = size(); i > 0; i--) for(int j = 1; j < i; j++) if(at(j-1) > at(j)) { // Swap the two elements: T t = at(j-1); at(j-1) = at(j); at(j) = t; } } // Partial specialization for pointers: template<class T> class Sorted<T*> : public std::vector<T*> { public: void sort(); }; template<class T> void Sorted<T*>::sort() { for(int i = size(); i > 0; i--) for(int j = 1; j < i; j++) if(*at(j-1) > *at(j)) { // Swap the two elements: T* t = at(j-1); at(j-1) = at(j); at(j) = t; } } // Full specialization for char*: template<> void Sorted<char*>::sort() { for(int i = size(); i > 0; i--) for(int j = 1; j < i; j++) if(strcmp(at(j-1), at(j)) > 0) { // Swap the two elements: char* t = at(j-1); at(j-1) = at(j); at(j) = t; } }
//: C19:Sorted.cpp // Testing template specialization #include "Sorted.h" #include "Urand.h" #include "../arraySize.h" #include <iostream> #include <string> using namespace std; char* words[] = { "is", "running", "big", "dog", "a", }; char* words2[] = { "this", "that", "theother", }; int main() { Sorted<int> is; Urand<47> rand; for(int i = 0; i < 15; i++) is.push_back(rand()); for(int l = 0; l < is.size(); l++) cout << is[l] << ' '; cout << endl; is.sort(); for(int l = 0; l < is.size(); l++) cout << is[l] << ' '; cout << endl; // Uses the template partial specialization: Sorted<string*> ss; for(int i = 0; i < asz(words); i++) ss.push_back(new string(words[i])); for(int i = 0; i < ss.size(); i++) cout << *ss[i] << ' '; cout << endl; ss.sort(); for(int i = 0; i < ss.size(); i++) cout << *ss[i] << ' '; cout << endl; // Uses the full char* specialization: Sorted<char*> scp; for(int i = 0; i < asz(words2); i++) scp.push_back(words2[i]); for(int i = 0; i < scp.size(); i++) cout << scp[i] << ' '; cout << endl; scp.sort(); for(int i = 0; i < scp.size(); i++) cout << scp[i] << ' '; cout << endl;
//: C19:Nobloat.h // Templatized InheritStack.cpp #ifndef NOBLOAT_H #define NOBLOAT_H #include "Stack4.h" template<class T> class NBStack : public Stack { public: void push(T* str) { Stack::push(str); } T* peek() const { return (T*)Stack::peek(); } T* pop() { return (T*)Stack::pop(); } ~NBStack(); }; // Defaults to heap objects & ownership: template<class T> NBStack<T>::~NBStack() { T* top = pop(); while(top) { delete top; top = pop(); } }