///////////////////////////////////////////////////////////////// // PTS.cpp - Issue #4 : partial template specialization // // // // Jim Fawcett, CSE687 - Object Oriented Design, Spring 2005 // ///////////////////////////////////////////////////////////////// // // Partial Template Specialization: // Allows you to specialize a subset of a class's template // parameters. // // Below we give an example of a smart pointer designed // to handle arrays of some fixed size, determined by the // integer template parameter. // // For non-arrays we specialize the template for size=1, // leaving the type parameter T unspecified. #include #include template class smartPtr { public: smartPtr(T* pTr = 0) { pTr_ = new T[size]; if(pTr) for(int i=0; i() { return pTr_; } T* operator+(size_t i) { return pTr_ + i; } T operator[] (int n) const { return pTr_[n]; } T& operator[](int n) { return pTr_[n]; } // other members private: T* pTr_; }; template class smartPtr { public: smartPtr(T* pTr) : pTr_(new T(*pTr)) {} ~smartPtr() { delete pTr_; } T& operator*() { return *pTr_; } T* operator->() { return pTr_; } // note that operator[] and operator+ are not supplied // other members private: T* pTr_; }; // void main() { std::cout << "\n Demonstrating Partial Template Specialization"; std::cout << "\n ===============================================\n"; std::cout << "\n Creating smart pointer to string array"; std::cout << "\n ----------------------------------------"; smartPtr spArray; std::cout << "\n defining string array elements through smart pointer indexing"; spArray[0] = "first string"; spArray[1] = "second string"; spArray[2] = "third string"; std::cout << "\n accessing string array contents using smart pointer dereferencing:"; for(int i=0; i<3; ++i) std::cout << "\n " << *(spArray + i); std::cout << "\n using smart pointer selection to access array element:"; std::cout << "\n first element of target string array has " << spArray->size() << " characters"; std::cout << "\n creating another smart pointer to the same array"; smartPtr spArray2(&spArray[0]); std::cout << "\n smart pointer indexing through array"; for(int i=0; i<3; ++i) std::cout << "\n " << spArray2[i]; std::cout << "\n"; std::cout << "\n Creating no array specialization of smart pointer referring to string"; std::cout << "\n -----------------------------------------------------------------------"; std::string s2 = "another string"; smartPtr spNoArray(&s2); std::cout << "\n using dereferencing to access string:"; std::cout << "\n " << *spNoArray; std::cout << "\n selecting target element:"; std::cout << "\n there are " << spNoArray->size() << " characters in this string"; std::cout << "\n\n"; }