C++ Library Extensions 2022.12.09
To help learn modern C++ programming
20-container_for_variants.cpp
Go to the documentation of this file.
1
2
3#include <tpf_output.hpp>
4
7
8namespace types = tpf::types;
9
10template<typename Type>
11auto to_ref(const Type& value)
12{
13 return std::ref(const_cast<Type&>(value));
14}
15
17{
18 using age_t = int;
19 using weight_t = double;
20 using name_t = const char*;
21
22 // we defined a container type to hold variants
23 using personal_info_t =
25
26 personal_info_t info; // container info of
27 // std::vector of std::variant<age_t, weight_t, name_t>
28
29 info.emplace_back(10);
30 info.emplace_back(20);
31 info.emplace_back(40.6);
32 info.emplace_back(50.7);
33 info.emplace_back("Thomas Kim");
34 info.emplace_back("Steve Park");
35
36 stream <<"The contents of info: " << info << endl;
37
38// std::vector<age_t> ages;
39// std::vector<weight_t> weights;
40// std::vector<name_t> names;
41
42// types::overloads filters
43// {
44// [&ages](const age_t& age) { ages.emplace_back(age); },
45// [&weights](const weight_t& weight) { weights.emplace_back(weight); },
46// [&names](const auto& name) { names.emplace_back(name); }
47// };
48
49 std::vector<std::reference_wrapper<age_t>> ages;
50 std::vector<std::reference_wrapper<weight_t>> weights;
51 std::vector<std::reference_wrapper<name_t>> names;
52
53// types::overloads filters
54// {
55// [&ages](const age_t& age) { ages.emplace_back(std::ref(const_cast<age_t&>(age))); },
56// [&weights](const weight_t& weight) { weights.emplace_back(std::ref(const_cast<weight_t&>(weight))); },
57// [&names](const auto& name) { names.emplace_back(std::ref(const_cast<name_t&>(name))); }
58// };
59
60 types::overloads filters
61 {
62 [&ages](const age_t& age)
63 { ages.emplace_back(to_ref(age)); },
64 [&weights](const weight_t& weight)
65 { weights.emplace_back(to_ref(weight)); },
66 [&names](const auto& name)
67 { names.emplace_back(to_ref(name)); }
68 };
69
70 filters.for_each(info);
71
72 stream <<"\nAges: " << ages << endl;
73 stream << "\nWeights: " << weights << endl;
74 stream << "\nNames: " << names << endl;
75}
76
77int main()
78{
80}
reference_wrapper< Type > ref(Type &val) noexcept
auto to_ref(const Type &value)
void how_to_filter_containers_for_variants()
tpf::sstream stream
Type to string name conversions are defined.
Definition: 31-visit.cpp:7
hidden::container_of_variants_t< ContainerType, ElementTypes... > container_of_variants_t
Definition: tpf_types.hpp:6618
constexpr auto endl
Definition: tpf_output.hpp:973
Stream output operators << are implemented.