Sams Teach Yourself C++ in 21 Days

(singke) #1
Templates 709

19


17: DoPrint(i);
18: return 0;
19: }

0 1 2 3 4

On lines 3–11, a template class named Printis defined. As you can see, this is a
standard template class. On lines 6–9, the operator ()is overloaded to take an
object and outputs it to the standard output. On line 15,DoPrintis defined as an instance
of the Printclass using an intvalue. With this, you can now use DoPrintjust like a
function to print any integer values, as shown on line 17. The standard algorithm classes
work just like DoPrint. They have overloaded the operator()so you can use them like
functions.

Nonmutating Sequence Operations
Nonmutating sequence operations are components from the algorithm library that per-
form operations that don’t change the elements in a sequence. These include operators
such as for_each(),find(),search(), and count().Listing 19.12 shows how to use a
function object and the for_eachalgorithm to print elements in a vector.

LISTING19.12 Using the for_each()Algorithm


0: #include <iostream>
1: #include <vector>
2: #include <algorithm>
3: using namespace std;
4:
5: template<class T>
6: class Print
7: {
8: public:
9: void operator()(const T& t)
10: {
11: cout << t << “ “;
12: }
13: };
14:
15: int main()
16: {
17: Print<int> DoPrint;
18: vector<int> vInt(5);
19:
20: for (int i = 0; i < 5; ++i)

OUTPUT


LISTING19.11 continued


ANALYSIS
Free download pdf