-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path07_static_polymorphism_1.cpp
77 lines (68 loc) · 1.94 KB
/
07_static_polymorphism_1.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
69
70
71
72
73
74
75
76
77
#include <array>
#include <iostream>
#include <tuple>
#include <utility>
#include <variant>
template <typename ConcreteItem>
class GlamorousItem {
public:
void appear_in_full_glory() {
static_cast<ConcreteItem*>(this)->appear_in_full_glory();
}
};
class PinkHeels : public GlamorousItem<PinkHeels> {
public:
void appear_in_full_glory() {
std::cout << "Pink high heels suddenly appeared in all their beauty\n";
}
};
class GoldenWatch : public GlamorousItem<GoldenWatch> {
public:
void appear_in_full_glory() {
std::cout << "Everyone wanted to watch this watch\n";
}
};
template <typename... Args>
using PreciousItems = std::tuple<GlamorousItem<Args>...>;
using GlamorousVariant = std::variant<PinkHeels, GoldenWatch>;
class CommonGlamorousItem {
public:
template <typename T>
requires std::is_base_of_v<GlamorousItem<T>, T>
explicit CommonGlamorousItem(T&& item) : item_{std::forward<T>(item)} {}
void appear_in_full_glory() {
std::visit(
[]<typename T>(GlamorousItem<T> item) { item.appear_in_full_glory(); },
item_);
}
private:
GlamorousVariant item_;
};
int main() {
{
auto glamorous_items = PreciousItems<PinkHeels, GoldenWatch>{};
std::apply(
[]<typename... T>(GlamorousItem<T>... items) {
(items.appear_in_full_glory(), ...);
},
glamorous_items);
}
std::cout << "---\n";
{
auto glamorous_items = std::array{GlamorousVariant{PinkHeels{}},
GlamorousVariant{GoldenWatch{}}};
for (auto& elem : glamorous_items) {
std::visit([]<typename T>(
GlamorousItem<T> item) { item.appear_in_full_glory(); },
elem);
}
}
std::cout << "---\n";
{
auto glamorous_items = std::array{CommonGlamorousItem{PinkHeels{}},
CommonGlamorousItem{GoldenWatch{}}};
for (auto& elem : glamorous_items) {
elem.appear_in_full_glory();
}
}
}