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 } ...

Get Essential C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.