//----------------------------------------------------------------- // // templates2.cpp // // Illustrating basic things about template classes // // written by: Simon Parsons // modified : 19th May 2010 // //----------------------------------------------------------------- #include using namespace std; // Template class definition template class aPair{ private: T values[2]; public: aPair(T first, T second){ values[0] = first; values[1] = second; } T getFirst(){ return values[0]; } T getSecond(); }; // External function definition template T aPair::getSecond(){ return values[1]; } // A template specialization --- if the pair is a pair of chars, then // we can print it. // // Note that we have to define all the bits that we want for the class, they // aren't inherited from the generic class template<> class aPair { private: char values[2]; public: aPair(char first, char second); void print(){ cout << values[0] << values [1] << endl; } }; // External function definition aPair::aPair(char first, char second){ values[0] = first; values[1] = second; } main(){ aPair p(1, 2); cout << p.getSecond() << endl; aPair q(1.1, 2.2); cout << q.getFirst() << endl; // q.print(); This line won't compile aPair r('h', 'i'); r.print(); }