]>
git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/hana/example/tutorial/introspection.json.cpp
d81dd001a14a894daa1549960d0855e1454df03c
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>
11 namespace hana
= boost::hana
;
12 using namespace std::literals
;
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::_
);
21 std::string
quote(std::string s
) { return "\"" + s
+ "\""; }
24 auto to_json(T
const& x
) -> decltype(std::to_string(x
)) {
25 return std::to_string(x
);
28 std::string
to_json(char c
) { return quote({c
}); }
29 std::string
to_json(std::string s
) { return quote(s
); }
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
);
41 return "{" + join(std::move(json
), ", ") + "}";
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
) {
53 return "[" + join(std::move(json
), ", ") + "]";
61 BOOST_HANA_DEFINE_STRUCT(Car
,
68 BOOST_HANA_DEFINE_STRUCT(Person
,
70 (std::string
, last_name
),
75 Car bmw
{"BMW", "Z3"}, audi
{"Audi", "A4"};
76 Person john
{"John", "Doe", 30};
78 auto tuple
= hana::make_tuple(john
, audi
, bmw
);
79 std::cout
<< to_json(tuple
) << std::endl
;