//----------------------------------------------------------------- // // templates1.cpp // // Illustrating basic things about template functions // // written by: Simon Parsons // modified : 19th May 2010 // //----------------------------------------------------------------- #include using namespace std; // Template function definitions // mmax template T mmax(T x, T y){ if(x > y){ return x; } else { return y; } } // gThan, with two parameter types template bool gThan(T x, U y){ if(x > y){ return true; } else { return false; } } // average, with a variable of unspecified type and an int parameter template T average(T *tArray, int number){ T tSum = 0; for(int i = 0; i < number; i++){ tSum += tArray[i]; } tSum /= number; return tSum; } main(){ int iValue = mmax(3, 7); double dValue = mmax(2.3, 6.5); char cValue = mmax('a', '6'); cout << "With ints " << iValue << endl; cout << "With doubles " << dValue << endl; cout << "With chars " << cValue << endl; if (gThan(7, 4.3)){ cout << "yes!" << endl; } int iArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; cout << average(iArray, 10) << endl; double dArray[] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10}; cout << average(dArray, 10) << endl; }