tailieunhanh - Chapter 11 - Templates

Several ways of relating templates and inheritance Class template derived from class-template specialization. Class template derived from non-template class, Class-template specialization derived from class-template specialization Non-template class derived from class-template specialization | Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class Templates and Nontype Parameters Templates and Inheritance Templates and Friends Templates and static Members Introduction Templates Function templates Specify entire range of related (overloaded) functions Function-template specializations Class templates Specify entire range of related classes Class-template specializations Function Templates Overloaded functions Similar operations Different types of data Function templates Identical operations Different types of data Single function template Compiler generates separate object-code functions Type checking Function Templates Function-template definitions Keyword template List formal type parameters in angle brackets () Each parameter preceded by keyword class or typename class and typename interchangeable template template Introduction Templates Function templates Specify entire range of related (overloaded) functions Function-template specializations Class templates Specify entire range of related classes Class-template specializations Function Templates Overloaded functions Similar operations Different types of data Function templates Identical operations Different types of data Single function template Compiler generates separate object-code functions Type checking Function Templates Function-template definitions Keyword template List formal type parameters in angle brackets () Each parameter preceded by keyword class or typename class and typename interchangeable template template template Specify types of Arguments to function Return type of function Variables within function (1 of 2) 1 // Fig. : 2 // Using template functions. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 // function template printArray definition 9 template 10 void printArray( const T *array, const int count ) 11 { 12 for ( int i = 0; i < count; i++ ) 13 cout << array[ i ] << " "; 14 15 cout << endl; 16 17 } // end function printArray 18 19 int main() 20 { 21 const int aCount = 5; 22 const int bCount = 7; 23 const int cCount = 6; 24 Function template definition; declare single formal type parameter T. T is type parameter; use any valid identifier. If T is user-defined type, stream-insertion operator must be overloaded for class T. (2 of 2) 25 int a[ aCount ] = { 1, 2, 3, 4, 5 }; 26 double b[ bCount ] = { , , , , , , }; 27 char c[ cCount ] = .