quickstart.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. // Make sure `assert` always triggers an assertion
  5. #ifdef NDEBUG
  6. # undef NDEBUG
  7. #endif
  8. //! [additional_setup]
  9. #include <cassert>
  10. #include <iostream>
  11. #include <string>
  12. struct Fish { std::string name; };
  13. struct Cat { std::string name; };
  14. struct Dog { std::string name; };
  15. //! [additional_setup]
  16. //! [includes]
  17. #include <boost/hana.hpp>
  18. namespace hana = boost::hana;
  19. //! [includes]
  20. int main() {
  21. //! [animals]
  22. auto animals = hana::make_tuple(Fish{"Nemo"}, Cat{"Garfield"}, Dog{"Snoopy"});
  23. //! [animals]
  24. //! [algorithms]
  25. using namespace hana::literals;
  26. // Access tuple elements with operator[] instead of std::get.
  27. Cat garfield = animals[1_c];
  28. // Perform high level algorithms on tuples (this is like std::transform)
  29. auto names = hana::transform(animals, [](auto a) {
  30. return a.name;
  31. });
  32. assert(hana::reverse(names) == hana::make_tuple("Snoopy", "Garfield", "Nemo"));
  33. //! [algorithms]
  34. //! [type-level]
  35. auto animal_types = hana::make_tuple(hana::type_c<Fish*>, hana::type_c<Cat&>, hana::type_c<Dog>);
  36. auto no_pointers = hana::remove_if(animal_types, [](auto a) {
  37. return hana::traits::is_pointer(a);
  38. });
  39. static_assert(no_pointers == hana::make_tuple(hana::type_c<Cat&>, hana::type_c<Dog>), "");
  40. //! [type-level]
  41. //! [has_name]
  42. auto has_name = hana::is_valid([](auto&& x) -> decltype((void)x.name) { });
  43. static_assert(has_name(garfield), "");
  44. static_assert(!has_name(1), "");
  45. //! [has_name]
  46. #if 0
  47. //! [screw_up]
  48. auto serialize = [](std::ostream& os, auto const& object) {
  49. hana::for_each(os, [&](auto member) {
  50. // ^^ oopsie daisy!
  51. os << member << std::endl;
  52. });
  53. };
  54. //! [screw_up]
  55. #endif
  56. //! [serialization]
  57. // 1. Give introspection capabilities to 'Person'
  58. struct Person {
  59. BOOST_HANA_DEFINE_STRUCT(Person,
  60. (std::string, name),
  61. (int, age)
  62. );
  63. };
  64. // 2. Write a generic serializer (bear with std::ostream for the example)
  65. auto serialize = [](std::ostream& os, auto const& object) {
  66. hana::for_each(hana::members(object), [&](auto member) {
  67. os << member << std::endl;
  68. });
  69. };
  70. // 3. Use it
  71. Person john{"John", 30};
  72. serialize(std::cout, john);
  73. // output:
  74. // John
  75. // 30
  76. //! [serialization]
  77. }