| 1 | // Copyright (c) 2020-2024 Antony Polukhin |
| 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 | #include <boost/core/lightweight_test.hpp> |
| 7 | |
| 8 | #include <boost/pfr/core.hpp> |
| 9 | |
| 10 | namespace some { |
| 11 | struct struct1{ int i; }; |
| 12 | struct struct2{ int i; short s; }; |
| 13 | } |
| 14 | |
| 15 | |
| 16 | void test_single_field() { |
| 17 | { |
| 18 | some::struct1 s{.i: 1}; |
| 19 | auto s_tuple = boost::pfr::structure_to_tuple(val: s); |
| 20 | BOOST_TEST_EQ(std::get<0>(s_tuple), 1); |
| 21 | |
| 22 | static_assert(std::is_same< |
| 23 | std::tuple<int>, decltype(s_tuple) |
| 24 | >::value, "" ); |
| 25 | } |
| 26 | { |
| 27 | const some::struct1 s{.i: 1}; |
| 28 | auto s_tuple = boost::pfr::structure_to_tuple(val: s); |
| 29 | BOOST_TEST_EQ(std::get<0>(s_tuple), 1); |
| 30 | |
| 31 | static_assert(std::is_same< |
| 32 | std::tuple<int>, decltype(s_tuple) |
| 33 | >::value, "" ); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | |
| 38 | void test_two_fields() { |
| 39 | { |
| 40 | some::struct2 s{.i: 1, .s: 2}; |
| 41 | auto s_tuple = boost::pfr::structure_to_tuple(val: s); |
| 42 | BOOST_TEST_EQ(std::get<0>(s_tuple), 1); |
| 43 | BOOST_TEST_EQ(std::get<1>(s_tuple), 2); |
| 44 | |
| 45 | static_assert(std::is_same< |
| 46 | std::tuple<int, short>, decltype(s_tuple) |
| 47 | >::value, "" ); |
| 48 | } |
| 49 | { |
| 50 | const some::struct2 s{.i: 1, .s: 2}; |
| 51 | auto s_tuple = boost::pfr::structure_to_tuple(val: s); |
| 52 | BOOST_TEST_EQ(std::get<0>(s_tuple), 1); |
| 53 | BOOST_TEST_EQ(std::get<1>(s_tuple), 2); |
| 54 | |
| 55 | static_assert(std::is_same< |
| 56 | std::tuple<int, short>, decltype(s_tuple) |
| 57 | >::value, "" ); |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | // Test from https://github.com/boostorg/pfr/issues/155 |
| 62 | void test_throwing_field() { |
| 63 | #if BOOST_PFR_USE_CPP17 || BOOST_PFR_USE_LOOPHOLE |
| 64 | struct throw_on_copy { |
| 65 | throw_on_copy() = default; |
| 66 | throw_on_copy(const throw_on_copy&){ throw 42; } |
| 67 | }; |
| 68 | |
| 69 | struct throwing_struct { |
| 70 | int i; |
| 71 | throw_on_copy s; |
| 72 | }; |
| 73 | |
| 74 | throwing_struct s {.i: 10, .s: {}}; |
| 75 | try { |
| 76 | std::tuple<int, throw_on_copy> t = boost::pfr::structure_to_tuple(val: s); |
| 77 | BOOST_TEST(false); // the above line should throw |
| 78 | (void)t; |
| 79 | } catch (...) {} |
| 80 | #endif |
| 81 | } |
| 82 | |
| 83 | int main() { |
| 84 | test_single_field(); |
| 85 | test_two_fields(); |
| 86 | test_throwing_field(); |
| 87 | |
| 88 | return boost::report_errors(); |
| 89 | } |
| 90 | |
| 91 | |
| 92 | |