C++ Library Extensions 2022.12.09
To help learn modern C++ programming
18-static_polymorphism.cpp
Go to the documentation of this file.
1#include <tpf_output.hpp>
2
5
6// mixin
7template<typename... CallbackTypes>
8struct callbacks: public CallbackTypes...
9{
10 using CallbackTypes::operator()...;
11};
12
13// variadic template argument deduction guide
14template<typename... CallbackTypes>
15callbacks(CallbackTypes...) -> callbacks<CallbackTypes...>;
16
18{
19 auto handle_int = [](int value)
20 {
21 stream <<"Integer value: " << value << endl;
22 };
23
24 auto handle_double = [](double value)
25 {
26 stream << "Double value: " << value << endl;
27 };
28
29 auto handle_const_char = [](const char* name)
30 {
31 stream << "Your name is " << name << endl;
32 };
33
34 auto catch_all = [](auto value)
35 {
36 stream << "Unclassified value: " << value << endl;
37 };
38
39 callbacks handle_callbacks{handle_int,
40 handle_double, handle_const_char, catch_all };
41
42 handle_callbacks(1);
43
44 handle_callbacks(22.0/7.0);
45
46 handle_callbacks("Thomas Kim");
47
48 handle_callbacks( std::string("Unclassified") );
49
50}
51
53{
54 using variant_t = std::variant<int, double, const char*>;
55
56 variant_t v;
57
58 auto handle_int = [](int value)
59 {
60 stream <<"Integer value: " << value << endl;
61 };
62
63 auto handle_double = [](double value)
64 {
65 stream << "Double value: " << value << endl;
66 };
67
68 auto handle_const_char = [](const char* name)
69 {
70 stream << "Your name is " << name << endl;
71 };
72
73 auto catch_all = [](auto value)
74 {
75 stream << "Unclassified value: " << value << endl;
76 };
77
78 callbacks handle_callbacks{handle_int,
79 handle_double, handle_const_char, catch_all };
80
81 v = 5;
82
83 auto handle_variant = [&handle_callbacks](auto& v)
84 {
85 std::visit(handle_callbacks, v);
86 };
87
88 handle_variant(v);
89
90 v = 22.0 / 7.0;
91
92 handle_variant(v);
93
94 v = "Thomas Kim";
95
96 handle_variant(v);
97}
98
99int main()
100{
101 // test_callbacks();
102
103 test_variant();
104}
callbacks(CallbackTypes...) -> callbacks< CallbackTypes... >
tpf::sstream stream
void test_variant()
int main()
void test_callbacks()
enable_if_variant_t< VariantType > visit(VisitorType &&visitor, VariantType &&vt)
Definition: 31-visit.cpp:118
constexpr auto endl
Definition: tpf_output.hpp:973
Stream output operators << are implemented.