• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright Louis Dionne 2013-2017
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>
join(Xs && xs,std::string sep)17 std::string join(Xs&& xs, std::string sep) {
18   return hana::fold(hana::intersperse(std::forward<Xs>(xs), sep), "", hana::_ + hana::_);
19 }
20 
quote(std::string s)21 std::string quote(std::string s) { return "\"" + s + "\""; }
22 
23 template <typename T>
to_json(T const & x)24 auto to_json(T const& x) -> decltype(std::to_string(x)) {
25   return std::to_string(x);
26 }
27 
to_json(char c)28 std::string to_json(char c) { return quote({c}); }
to_json(std::string s)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,
to_json(T const & x)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,
to_json(Xs const & xs)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 
main()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{"BMW", "Z3"}, audi{"Audi", "A4"};
76 Person john{"John", "Doe", 30};
77 
78 auto tuple = hana::make_tuple(john, audi, bmw);
79 std::cout << to_json(tuple) << std::endl;
80 //! [usage]
81 }
82