I l@ve RuBoard Previous Section Next Section

Exercise 2.6

Reimplement the functions of Exercise 2.5 using templates. Modify the main() function accordingly.

The nine nontemplate max() functions are replaced by three max() function templates. main() does not require any changes.



#include <string> 


#include <vector> 


#include <algorithm> 


using namespace std; 





template <typename Type> 


inline Type max( Type t1, Type t2 ){ return t1 > t2 ? t1 : t2; } 





template <typename elemType> 


inline elemType max( const vector<elemType> &vec ) 


       { return *max_element( vec.begin(), vec.end() ); } 





template <typename arrayType> 


inline arrayType max( const arrayType *parray, int size ) 


       { return *max_element( parray, parray+size ); } 





// note: no changes required of main()! 


int main() { 


    // same as in exercise 2.4 


} 

When compiled and executed, this program generates the same output as the program in Exercise 2.5.

    I l@ve RuBoard Previous Section Next Section