]>
git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/hana/example/wandbox.cpp
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)
5 #include <boost/hana.hpp>
10 #include <type_traits>
12 namespace hana
= boost::hana
;
13 using namespace hana::literals
;
14 using namespace std::literals
;
17 //////////////////////////////////////////////////////////////////////////////
20 // You can play around and press 'Run' at the bottom of this file to compile
23 // To get you started, here's a small JSON generator written with Hana
24 // (this is explained in the tutorial if you're interested):
25 //////////////////////////////////////////////////////////////////////////////
27 // 1. Define some utilities
28 template <typename Xs
>
29 std::string
join(Xs
&& xs
, std::string sep
) {
30 return hana::fold(hana::intersperse(std::forward
<Xs
>(xs
), sep
), "", std::plus
<>{});
33 std::string
quote(std::string s
) { return "\"" + s
+ "\""; }
36 auto to_json(T
const& x
) -> decltype(std::to_string(x
)) {
37 return std::to_string(x
);
40 std::string
to_json(char c
) { return quote({c
}); }
41 std::string
to_json(std::string s
) { return quote(s
); }
44 // 2. Define how to print user-defined types
46 std::enable_if_t
<hana::Struct
<T
>::value
,
47 std::string
> to_json(T
const& x
) {
48 auto json
= hana::transform(hana::keys(x
), [&](auto name
) {
49 auto const& member
= hana::at_key(x
, name
);
50 return quote(hana::to
<char const*>(name
)) + " : " + to_json(member
);
53 return "{" + join(std::move(json
), ", ") + "}";
56 // 3. Define how to print Sequences
57 template <typename Xs
>
58 std::enable_if_t
<hana::Sequence
<Xs
>::value
,
59 std::string
> to_json(Xs
const& xs
) {
60 auto json
= hana::transform(xs
, [](auto const& x
) {
64 return "[" + join(std::move(json
), ", ") + "]";
68 // 4. Create your own types and make them compatible with Hana.
69 // This can be done intrusively or non-intrusively.
71 BOOST_HANA_DEFINE_STRUCT(Car
,
78 // 5. Generate beautiful JSON without hassle. Enjoy!
79 auto cars
= hana::make_tuple(
82 Car
{"Ferrari", "F40"},
83 Car
{"Lamborghini", "Diablo"}
87 std::cout
<< to_json(cars
) << std::endl
;