-
Notifications
You must be signed in to change notification settings - Fork 0
/
type_erasure.cpp
63 lines (48 loc) · 976 Bytes
/
type_erasure.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
#include <iostream>
#include <memory>
#include <vector>
struct knight
{
void attack() { std::cout << "draw sword\n"; }
};
struct mage
{
void attack() { std::cout << "spell magic curse\n"; }
};
struct unit
{
template <typename T>
unit(T&& obj) : unit_(std::make_shared<unit_model<T>>(std::forward<T>(obj))) {}
void attack()
{
unit_->attack();
}
struct unit_concept
{
virtual void attack() = 0;
virtual ~unit_concept() = default;
};
template <typename T>
struct unit_model : public unit_concept
{
unit_model(T& unit) : t(unit) {}
void attack() override { t.attack(); }
private:
T& t;
};
private:
std::shared_ptr<unit_concept> unit_;
};
void fight(std::vector<unit>& units)
{
for (auto& u : units)
u.attack();
}
int main()
{
knight k;
mage m;
std::vector<unit> v{ unit(k), unit(m) };
fight(v);
return 0;
}