-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvisitor2.cpp
68 lines (60 loc) · 1.24 KB
/
visitor2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* \file
* \brief
*
* \todo
*/
/*
Visitor provides a call-back for every item in a collection.
This allows the implementation of the collection to hidden.
visitor1.cpp is the simplest type of visitor using templates.
The std::for_each template function that takes any kind of type.
visitor2.cpp uses the more traditional inheritance-based polymorphism.
*/
#include <vector>
#include <string>
#include <iostream>
class Visitor
{
public:
virtual ~Visitor() { }
virtual void on_recipient(const std::string &)=0;
};
class Recipients
{
std::vector<std::string> recipients;
public:
void add_recipient(const std::string & recipient)
{
recipients.push_back(recipient);
}
void visit(Visitor & visitor) const
{
for(std::vector<std::string>::const_iterator recipient = recipients.begin();
recipient != recipients.end();
++recipient)
{
visitor.on_recipient(*recipient);
}
}
};
class PrintHello : public Visitor
{
public:
void on_recipient(const std::string & recipient)
{
std::cout << "Hello " << recipient << "!" << std::endl;
}
};
void hello_world(Visitor & visitor)
{
Recipients recipients;
recipients.add_recipient("world");
recipients.visit(visitor);
}
int main()
{
PrintHello visitor;
hello_world(visitor);
return 0;
}