Naturally, yes. Templates are used a lot in the C++ Standard Library.
Containers and Algorithms (which you'll find very useful, unless you're hellbent on reinventing the wheel) are implemented as class templates and function templates, respectively.
http://www.cplusplus.com/reference/stl/
http://www.cplusplus.com/reference/algorithm/
Templates allow you to write generic code.
The idea behind generic code revolves around letting the C++ compiler fill out the appropriate types in your code (as you write your algorithm to work identically for most types).
Non-template version of a
max() function:
1 2 3 4 5 6 7 8
|
// good and clean, but only used for int's
int max(int a, int b)
{
if (a > b)
return a;
return b;
}
|
The template version of the
max() function:
1 2 3 4 5 6 7 8
|
template <typename Number>
Number max(Number a, Number b)
{
if (a > b)
return a;
return b;
}
|
Notice how the algorithm inside the two versions is exactly the same.
However now, the
max() function template will be used automatically for any type that can be compared by
operator> without us having to write multiple versions of
max().
Edit: also, the type name "Number" is just a hint to fellow programmers that the function template should be used with numbers. It doesn't stop them from using our
max() on
std::string's for example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <iostream>
#include <string>
namespace test
{
template <typename Number>
Number max(Number a, Number b)
{
if (a > b)
return a;
return b;
}
}
int main()
{
std::string s1("Andrew");
std::string s2("Xavier");
std::cout << test::max(s1, s2) << std::endl;
}
|
Xavier
|
Above the
max() function template is put in the
test namespace because there already exists
max() in the
std namespace, provided by the C++ Standard Library.
http://www.cplusplus.com/reference/algorithm/max/