Saturday, May 9, 2009

Question on C++ Templates... This is the last question on my review and I seem to not grasp the question?

Write a C++ function using a template called findmax that takes two numeric input parameters (all of the same type), and returns the larger of the two. Note that the input parameters can be int, float, double, or long.

Question on C++ Templates... This is the last question on my review and I seem to not grasp the question?
A function template lets you define parameters of a generic type. When the compiler parses the function call it then fills the function in with the proper datatype. This lets you call a single function definition with multiple types.





Example for adding two numbers (it should be simple for you to modify it to find the maximum):





#include %26lt;iostream%26gt;


using namespace std;





template %26lt;class T%26gt;


T add(T a, T b)


{


 return (a + b);


}





int main()


{


 cout %26lt;%26lt; add(3,4) %26lt;%26lt; endl;


 cout %26lt;%26lt; add(54.2, 32.4) %26lt;%26lt; endl;


 return 0;


}


No comments:

Post a Comment