// Templatorama.cpp // NKU CSC 601 - Fall 2002 - Kirby // ----------------------------------------------------------------- // Examples reviewing some common (and rare) template constructions. // Based on examples in class, 9/26. // // (Will not compile on VC++6; requires VC++7, BCC32 5.5, GCC, ...) // ----------------------------------------------------------------- template< typename T > struct Pair { T first, second ; } ; template< typename T> struct Triple { T first, second, third ; } ; template< typename T, int N > class Array { public: // Class information typedef T ElementType ; static int length() throw() { return N ; } // Inspectors const T& operator[]( int i ) const throw() { return _a[i]; } // Mutators T& operator[]( int i ) throw() { return _a[i] ; } private: T _a[N] ; } ; /* Questions for discussion: Array. 1. Why would one want an Array metatype with the length (N) as a template parameter?! 2. The typedef class member seems (a) bizarre, and (b) pointless. What's it for? */ template< typename TComparable > const TComparable& min( const TComparable& o1, const TComparable o2 ) // no exception spec here { return ( o1 < o2 ) ? o1 : o2 ; } /* Questions for discussion: min 1. How does this differ from the pure OO ("IComparable" interface) approach? 2. Why does generic programming depend more on operator overloading than OO programming? 3. Sometime in the Spring of 2002, Stroustrup said "exception specifications are a failed experiment" [see Schmidt's "Deep C++" Column, 8/26/02, at msdn.microsoft.com]. Given that generic programming is moving to the fore in C++, do you agree with Bjarne? */ template< template< typename T > class Tuple > struct Geometry { Tuple iv ; Tuple rv ; } ; /* Question for discussion: Geometry 1. What the hell is this thing? */ #include #include using namespace std ; void main() { Array< string, 10 > names ; names[0]= "cat" ; cout << names.length() << endl ; Geometry< Pair > g2d ; Geometry< Triple > g3d ; g2d.iv.first= 23 ; g2d.rv.first= 2.32 ; g3d.rv.second= 2.32 ; }