| 1 | // Copyright Louis Dionne 2013-2022 |
| 2 | // Distributed under the Boost Software License, Version 1.0. |
| 3 | // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) |
| 4 | |
| 5 | #include <boost/hana.hpp> |
| 6 | |
| 7 | #include <iostream> |
| 8 | #include <string> |
| 9 | #include <type_traits> |
| 10 | #include <utility> |
| 11 | namespace hana = boost::hana; |
| 12 | using namespace std::literals; |
| 13 | |
| 14 | |
| 15 | //! [utilities] |
| 16 | template <typename Xs> |
| 17 | std::string join(Xs&& xs, std::string sep) { |
| 18 | return hana::fold(hana::intersperse(std::forward<Xs>(xs), sep), "" , hana::_ + hana::_); |
| 19 | } |
| 20 | |
| 21 | std::string quote(std::string s) { return "\"" + s + "\"" ; } |
| 22 | |
| 23 | template <typename T> |
| 24 | auto to_json(T const& x) -> decltype(std::to_string(x)) { |
| 25 | return std::to_string(x); |
| 26 | } |
| 27 | |
| 28 | std::string to_json(char c) { return quote(s: {c}); } |
| 29 | std::string to_json(std::string s) { return quote(s); } |
| 30 | //! [utilities] |
| 31 | |
| 32 | //! [Struct] |
| 33 | template <typename T> |
| 34 | std::enable_if_t<hana::Struct<T>::value, |
| 35 | std::string> to_json(T const& x) { |
| 36 | auto json = hana::transform(hana::keys(x), [&](auto name) { |
| 37 | auto const& member = hana::at_key(x, name); |
| 38 | return quote(hana::to<char const*>(name)) + " : " + to_json(member); |
| 39 | }); |
| 40 | |
| 41 | return "{" + join(std::move(json), ", " ) + "}" ; |
| 42 | } |
| 43 | //! [Struct] |
| 44 | |
| 45 | //! [Sequence] |
| 46 | template <typename Xs> |
| 47 | std::enable_if_t<hana::Sequence<Xs>::value, |
| 48 | std::string> to_json(Xs const& xs) { |
| 49 | auto json = hana::transform(xs, [](auto const& x) { |
| 50 | return to_json(x); |
| 51 | }); |
| 52 | |
| 53 | return "[" + join(std::move(json), ", " ) + "]" ; |
| 54 | } |
| 55 | //! [Sequence] |
| 56 | |
| 57 | |
| 58 | int main() { |
| 59 | //! [usage] |
| 60 | struct Car { |
| 61 | BOOST_HANA_DEFINE_STRUCT(Car, |
| 62 | (std::string, brand), |
| 63 | (std::string, model) |
| 64 | ); |
| 65 | }; |
| 66 | |
| 67 | struct Person { |
| 68 | BOOST_HANA_DEFINE_STRUCT(Person, |
| 69 | (std::string, name), |
| 70 | (std::string, last_name), |
| 71 | (int, age) |
| 72 | ); |
| 73 | }; |
| 74 | |
| 75 | Car bmw{.brand: "BMW" , .model: "Z3" }, audi{.brand: "Audi" , .model: "A4" }; |
| 76 | Person john{.name: "John" , .last_name: "Doe" , .age: 30}; |
| 77 | |
| 78 | auto tuple = hana::make_tuple(john, audi, bmw); |
| 79 | std::cout << to_json(xs: tuple) << std::endl; |
| 80 | //! [usage] |
| 81 | } |
| 82 | |