-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy path08_type_erasure.cpp
More file actions
51 lines (42 loc) · 1.16 KB
/
08_type_erasure.cpp
File metadata and controls
51 lines (42 loc) · 1.16 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
#include <array>
#include <iostream>
#include <memory>
class GlamorousItem {
public:
template <class T>
explicit GlamorousItem(T &&t)
: item_{std::make_unique<TypeErasedItem<T>>(std::forward<T>(t))} {}
void appear_in_full_glory() { item_->appear_in_full_glory_impl(); }
private:
struct TypeErasedItemBase {
virtual ~TypeErasedItemBase() = default;
virtual void appear_in_full_glory_impl() = 0;
};
template <class T> class TypeErasedItem final : public TypeErasedItemBase {
public:
explicit TypeErasedItem(T &&t) : t_{std::forward<T>(t)} {}
void appear_in_full_glory_impl() override { t_.appear_in_full_glory(); }
private:
T t_;
};
std::unique_ptr<TypeErasedItemBase> item_;
};
class PinkHeels {
public:
void appear_in_full_glory() {
std::cout << "Pink high heels suddenly appeared in all their beauty\n";
}
};
class GoldenWatch {
public:
void appear_in_full_glory() {
std::cout << "Everyone wanted to watch this watch\n";
}
};
int main() {
auto glamorous_items =
std::array{GlamorousItem{PinkHeels{}}, GlamorousItem{GoldenWatch{}}};
for (auto &item : glamorous_items) {
item.appear_in_full_glory();
}
}