wandbox.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. #include <boost/hana.hpp>
  5. #include <functional>
  6. #include <iostream>
  7. #include <string>
  8. #include <type_traits>
  9. #include <utility>
  10. namespace hana = boost::hana;
  11. using namespace hana::literals;
  12. using namespace std::literals;
  13. //////////////////////////////////////////////////////////////////////////////
  14. // Welcome to Hana!
  15. //
  16. // You can play around and press 'Run' at the bottom of this file to compile
  17. // and run this code.
  18. //
  19. // To get you started, here's a small JSON generator written with Hana
  20. // (this is explained in the tutorial if you're interested):
  21. //////////////////////////////////////////////////////////////////////////////
  22. // 1. Define some utilities
  23. template <typename Xs>
  24. std::string join(Xs&& xs, std::string sep) {
  25. return hana::fold(hana::intersperse(std::forward<Xs>(xs), sep), "", std::plus<>{});
  26. }
  27. std::string quote(std::string s) { return "\"" + s + "\""; }
  28. template <typename T>
  29. auto to_json(T const& x) -> decltype(std::to_string(x)) {
  30. return std::to_string(x);
  31. }
  32. std::string to_json(char c) { return quote({c}); }
  33. std::string to_json(std::string s) { return quote(s); }
  34. // 2. Define how to print user-defined types
  35. template <typename T>
  36. std::enable_if_t<hana::Struct<T>::value,
  37. std::string> to_json(T const& x) {
  38. auto json = hana::transform(hana::keys(x), [&](auto name) {
  39. auto const& member = hana::at_key(x, name);
  40. return quote(hana::to<char const*>(name)) + " : " + to_json(member);
  41. });
  42. return "{" + join(std::move(json), ", ") + "}";
  43. }
  44. // 3. Define how to print Sequences
  45. template <typename Xs>
  46. std::enable_if_t<hana::Sequence<Xs>::value,
  47. std::string> to_json(Xs const& xs) {
  48. auto json = hana::transform(xs, [](auto const& x) {
  49. return to_json(x);
  50. });
  51. return "[" + join(std::move(json), ", ") + "]";
  52. }
  53. // 4. Create your own types and make them compatible with Hana.
  54. // This can be done intrusively or non-intrusively.
  55. struct Car {
  56. BOOST_HANA_DEFINE_STRUCT(Car,
  57. (std::string, brand),
  58. (std::string, model)
  59. );
  60. };
  61. int main() {
  62. // 5. Generate beautiful JSON without hassle. Enjoy!
  63. auto cars = hana::make_tuple(
  64. Car{"BMW", "Z3"},
  65. Car{"Audi", "A4"},
  66. Car{"Ferrari", "F40"},
  67. Car{"Lamborghini", "Diablo"}
  68. // ...
  69. );
  70. std::cout << to_json(cars) << std::endl;
  71. }