2
0
mirror of https://github.com/boostorg/pfr.git synced 2026-01-19 04:22:13 +00:00

A few more examples

This commit is contained in:
Antony Polukhin
2016-12-31 21:42:44 +03:00
parent 9bca907657
commit 459a25f817
4 changed files with 200 additions and 3 deletions

View File

@@ -98,6 +98,137 @@ assert(r == 11);
(void)r;
}
#include <iostream>
#include <boost/type_index.hpp>
namespace quick_examples_ns {
//[pfr_quick_examples_structures
struct foo {
int integer;
double real;
void operator +=(int v) {
integer += v * 10;
real += v * 100;
}
};
struct bar {
char character;
foo f;
};
bar var{'A', {777, 3.141593}};
//]
inline std::ostream& operator<<(std::ostream& os, const bar& b) {
return os << '{' << b.character << ", {" << b.f.integer << ", " << b.f.real << "}}";
}
void test_examples() {
{
bar var{'A', {777, 3.141593}};
//[pfr_quick_examples_flat_for_each
// incrementing each field on 1:
boost::pfr::flat_for_each_field(var, [](auto& field) {
field += 1;
});
//]
std::cout << "flat_for_each_field outputs:\n" << var << '\n';
}
{
bar var{'A', {777, 3.141593}};
//[pfr_quick_examples_for_each
// incrementing first field on 1 and calling foo::operator+= for second field:
boost::pfr::for_each_field(var, [](auto& field) {
field += 1;
});
//]
std::cout << "flat_for_each_field outputs:\n" << var << '\n';
}
{
bar var{'A', {777, 3.141593}};
//[pfr_quick_examples_flat_for_each_idx
boost::pfr::flat_for_each_field(var, [](const auto& field, std::size_t idx) {
std::cout << idx << ": " << boost::typeindex::type_id_runtime(field) << '\n';
});
//]
}
{
bar var{'A', {777, 3.141593}};
//[pfr_quick_examples_for_each_idx
boost::pfr::for_each_field(var, [](const auto& field, std::size_t idx) {
std::cout << idx << ": " << boost::typeindex::type_id_runtime(field) << '\n';
});
//]
}
{
//[pfr_quick_examples_tuple_size
std::cout << "tuple_size: " << boost::pfr::tuple_size<bar>::value << '\n';
//]
}
{
//[pfr_quick_examples_flat_tuple_size
std::cout << "flat_tuple_size: " << boost::pfr::flat_tuple_size<bar>::value << '\n';
//]
}
#if __cplusplus >= 201606L /* Oulu meeting, not the exact value */
{
bar var{'A', {777, 3.141593}};
//[pfr_quick_examples_get_1
boost::pfr::get<1>(var) = foo{1, 2}; // C++17 is required
//]
std::cout << "boost::pfr::get<1>(var) outputs:\n" << var << '\n';
}
#endif
{
bar var{'A', {777, 3.141593}};
//[pfr_quick_examples_flat_get_1
boost::pfr::flat_get<1>(var) = 1;
//]
std::cout << "boost::pfr::flat_get<1>(var) outputs:\n" << var << '\n';
}
{
bar var{'A', {777, 3.141593}};
//[pfr_quick_examples_get_2
boost::pfr::get<1>(var.f) = 42.01;
//]
std::cout << "boost::pfr::get<1>(var.f) outputs:\n" << var << '\n';
}
{
bar var{'A', {777, 3.141593}};
//[pfr_quick_examples_flat_get_2
boost::pfr::flat_get<1>(var.f) = 42.01;
//]
std::cout << "boost::pfr::flat_get<1>(var.f) outputs:\n" << var << '\n';
}
}
} // namespace for_each_field_ex
int main() {
example_get();
quick_examples_ns::test_examples();
}