Simple Min and Max Functions
#include <iostream> #include <string> using std::string; /* * Template functions can create generic versions of functions. * * Note: There are min() and max() in the standard library, which * should be inaccessible without the std:: prefix, but the code * breaks anyway, so I had to change the names. */ template <typename T> T minimum(const T a, const T b) { if(a < b) return a; else return b; } template <typename T> T maximum(const T a, const T b) { if(a < b) return b; else return a; } main() { std::cout << minimum(15, 46) << " " << maximum(58,32) << std::endl; std::cout << minimum(4.8, -5.6) << " " << maximum(3.45,32.33) << " " << maximum(-4.4, -8.52) << " " << maximum<double>(4.8, 7) << std::endl; std::cout << minimum(string("Fred"), string("Barney")) << " " << maximum(string("Alice"), string("Sally")) << std::endl; }

This file demonstrates two simple template functions, to find the minimum and maximum of two parameters. The parameter T (in each) represents some type name. This allows the function to operate on any type of arguments for which the < operator is defined. Notice that T is used to declare the parameters of the function, so each of the parameters must be of type <, which is not known until the function is used.

When calling the function, it is not usually necessary to state the parameter value (some type). But do notice the call maximum<double>(4.8, 7) about half-way through. When you do need to explicitly state the template parameter value(s), do so in angle brackets after the name as shown. It is necessary here because the two arguments have different types, and so don't determine the value of T. We specify the value of T to be double, then the compiler will convert the integer.

Note that the function is written under the assumption that the less than operator is defined for type T. This fact is not declared anywhere, but if you try it, you'll get a compiler error at the point call. (Two vectors should break, or a simply class you create.)