| 1 | // Copyright 2016-2024 Antony Polukhin |
| 2 | |
| 3 | // Distributed under the Boost Software License, Version 1.0. |
| 4 | // (See the accompanying file LICENSE_1_0.txt |
| 5 | // or a copy at <http://www.boost.org/LICENSE_1_0.txt>.) |
| 6 | |
| 7 | //[pfr_example_get |
| 8 | /*` |
| 9 | The following example shows how to access structure fields by index using [funcref boost::pfr::get]. |
| 10 | |
| 11 | Let's define some structure: |
| 12 | */ |
| 13 | #include <boost/pfr/core.hpp> |
| 14 | |
| 15 | struct foo { // defining structure |
| 16 | int some_integer; |
| 17 | char c; |
| 18 | }; |
| 19 | |
| 20 | /*` |
| 21 | We can access fields of that structure by index: |
| 22 | */ |
| 23 | foo f {.some_integer: 777, .c: '!'}; |
| 24 | auto& r1 = boost::pfr::get<0>(val&: f); // accessing field with index 0, returns reference to `foo::some_integer` |
| 25 | auto& r2 = boost::pfr::get<1>(val&: f); // accessing field with index 1, returns reference to `foo::c` |
| 26 | //] [/pfr_example_get] |
| 27 | |
| 28 | |
| 29 | int main() { |
| 30 | if (r1 != 777) return 1; |
| 31 | if (r2 != '!') return 2; |
| 32 | |
| 33 | r1 = 42; |
| 34 | r2 = 'A'; |
| 35 | |
| 36 | if (r1 != 42) return 3; |
| 37 | if (r2 != 'A') return 4; |
| 38 | if (f.some_integer != 42) return 5; |
| 39 | if (f.c != 'A') return 6; |
| 40 | |
| 41 | return 0; |
| 42 | } |
| 43 | |