| 1 | // Copyright (c) 2023 Bela Schaum, X-Ryl669, Denis Mikhailov. |
| 2 | // |
| 3 | // Distributed under the Boost Software License, Version 1.0. (See accompanying |
| 4 | // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) |
| 5 | |
| 6 | |
| 7 | // Initial implementation by Bela Schaum, https://github.com/schaumb |
| 8 | // The way to make it union and UB free by X-Ryl669, https://github.com/X-Ryl669 |
| 9 | // |
| 10 | |
| 11 | #include <boost/pfr/config.hpp> |
| 12 | |
| 13 | #if BOOST_PFR_CORE_NAME_ENABLED && BOOST_PFR_USE_CPP17 |
| 14 | //[pfr_example_get_name |
| 15 | /*` |
| 16 | Since C++20 it's possible to read name of a structure field by index using Boost.PFR library. |
| 17 | The following example shows how to do it using [funcref boost::pfr::get_name]. |
| 18 | |
| 19 | Let's define some structure: |
| 20 | */ |
| 21 | #include <boost/pfr/core_name.hpp> |
| 22 | |
| 23 | struct foo { // defining structure |
| 24 | int some_integer; |
| 25 | char c; |
| 26 | }; |
| 27 | |
| 28 | /*` |
| 29 | We can access field's names of that structure by index: |
| 30 | */ |
| 31 | constexpr std::string_view n1 = boost::pfr::get_name<0, foo>(); // returns "some_integer" |
| 32 | constexpr std::string_view n2 = boost::pfr::get_name<1, foo>(); // returns "c" |
| 33 | //] [/pfr_example_get_name] |
| 34 | #endif |
| 35 | |
| 36 | int main() { |
| 37 | #if BOOST_PFR_CORE_NAME_ENABLED && BOOST_PFR_USE_CPP17 |
| 38 | if (n1 != "some_integer" ) return 1; |
| 39 | if (n2 != "c" ) return 2; |
| 40 | #endif |
| 41 | |
| 42 | return 0; |
| 43 | } |
| 44 | |