-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate_example.cpp
More file actions
71 lines (53 loc) · 1.35 KB
/
Copy pathtemplate_example.cpp
File metadata and controls
71 lines (53 loc) · 1.35 KB
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
69
70
71
// template_example.cpp
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <vector>
#include "delegate.hpp"
template <typename T>
class Base {
public:
virtual ~Base() = default;
Delegate<void(const T&, std::size_t)> OnItemAdded;
virtual bool add(const T& value) {
items_.push_back(value);
OnItemAdded(value, items_.size());
return true;
}
const std::vector<T>& items() const { return items_; }
protected:
bool contains(const T& value) const { return std::find(items_.begin(), items_.end(), value) != items_.end(); }
private:
std::vector<T> items_;
};
class IntContainer : public Base<int> {
public:
bool add(const int& value) override {
if (this->contains(value)) {
std::cout << value << " already exists, skip" << '\n';
return false;
}
return Base<int>::add(value);
}
};
class Printer {
public:
void onItemAdded(const int& value, std::size_t size) {
std::cout << "added number: " << value << ", current size: " << size << '\n';
}
};
int main() {
IntContainer container;
Printer printer;
container.OnItemAdded.add(&printer, &Printer::onItemAdded);
container.add(10);
container.add(20);
container.add(10);
container.add(30);
std::cout << "final values:";
for (int value : container.items()) {
std::cout << ' ' << value;
}
std::cout << '\n';
return 0;
}