C++ Library Extensions 2022.12.09
To help learn modern C++ programming
16-advanced_mixin.cpp
Go to the documentation of this file.
1#include <tpf_output.hpp>
2
5
6struct Dog
7{
8 std::string m_name;
9
10 void operator()() const
11 {
12 stream <<"I am a dog. My name is " << m_name << endl;
13 }
14};
15
16struct Cat
17{
18 std::string m_name;
19
20 void operator()() const
21 {
22 stream <<"I am a cat. My name is " << m_name << endl;
23 }
24};
25
26struct Cow
27{
28 std::string m_name;
29 double m_weight;
30
31 void operator()()const
32 {
33 stream <<"I am a cow. My name is " << m_name <<", I weigh "
34 << m_weight << " kg." << endl;
35 }
36};
37
38template<typename... Animals>
39struct AnimalFarm: public Animals... // mixin
40{
41 using Animals::operator()...;
42
44
45 AnimalFarm(Animals... animals): Animals{ std::move(animals) } ... { }
46
47 template<size_t type_index>
48 void report()
49 {
50 // we select type_index-th base class type
51 using base_type =
53
54 // we are calling base type's function-call operator
55 base_type::operator()();
56 }
57
58 template<size_t StartIndex, size_t EndIndex>
60 {
61 static void report(const AnimalFarm& af)
62 {
63 if constexpr(StartIndex < EndIndex)
64 {
65 using base_type =
67
68 auto& base = static_cast<const base_type&>(af);
69
70 base.operator()();
71 }
72
73 if constexpr(StartIndex + 1 < EndIndex)
74 {
76 }
77 }
78
79 };
80
81 void operator()() const
82 {
83 static_loop<0, tpf::types::type_count_v<Animals...> >::report(*this);
84 }
85};
86
87// Class Template Argument Deduction Guide
88template<typename... Animals>
89AnimalFarm(Animals...) -> AnimalFarm<Animals...>;
90
92
94{
95 Cat cat{"Thomas the Cat"};
96
97 AnimalFarm myfarm { cat, Dog{"Dog the Friendly"}, Cow{"Pretty Cow", 500.0} };
98
99 myfarm.report<animal::first_animal>();
100 myfarm.report<animal::second_animal>();
101 myfarm.report<animal::third_animal>();
102
103 stream << "List all animals " << endl;
104
105 myfarm();
106}
107
108int main()
109{
111}
tpf::sstream stream
@ first_animal
@ third_animal
@ second_animal
void test_animal_farm()
AnimalFarm(Animals...) -> AnimalFarm< Animals... >
auto endl
int main()
hidden::select_nth_type_t< SelectIndex, Types... > select_nth_type_t
Definition: tpf_types.hpp:5585
constexpr auto type_count_v
Definition: tpf_types.hpp:3158
constexpr auto endl
Definition: tpf_output.hpp:973
static void report(const AnimalFarm &af)
void operator()() const
AnimalFarm(Animals... animals)
void operator()() const
std::string m_name
void operator()() const
double m_weight
std::string m_name
void operator()() const
std::string m_name
This type is used to manipulate type list.
Definition: tpf_types.hpp:956
Stream output operators << are implemented.