overview.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. //////////////////////////////////////////////////////////////////////////////
  9. // Important: Keep this file in sync with the Overview in the README
  10. //////////////////////////////////////////////////////////////////////////////
  11. #include <boost/hana.hpp>
  12. #include <cassert>
  13. #include <string>
  14. namespace hana = boost::hana;
  15. using namespace hana::literals;
  16. struct Fish { std::string name; };
  17. struct Cat { std::string name; };
  18. struct Dog { std::string name; };
  19. int main() {
  20. // Sequences capable of holding heterogeneous objects, and algorithms
  21. // to manipulate them.
  22. auto animals = hana::make_tuple(Fish{"Nemo"}, Cat{"Garfield"}, Dog{"Snoopy"});
  23. auto names = hana::transform(animals, [](auto a) {
  24. return a.name;
  25. });
  26. assert(hana::reverse(names) == hana::make_tuple("Snoopy", "Garfield", "Nemo"));
  27. // No compile-time information is lost: even if `animals` can't be a
  28. // constant expression because it contains strings, its length is constexpr.
  29. static_assert(hana::length(animals) == 3u, "");
  30. // Computations on types can be performed with the same syntax as that of
  31. // normal C++. Believe it or not, everything is done at compile-time.
  32. auto animal_types = hana::make_tuple(hana::type_c<Fish*>, hana::type_c<Cat&>, hana::type_c<Dog*>);
  33. auto animal_ptrs = hana::filter(animal_types, [](auto a) {
  34. return hana::traits::is_pointer(a);
  35. });
  36. static_assert(animal_ptrs == hana::make_tuple(hana::type_c<Fish*>, hana::type_c<Dog*>), "");
  37. // And many other goodies to make your life easier, including:
  38. // 1. Access to elements in a tuple with a sane syntax.
  39. static_assert(animal_ptrs[0_c] == hana::type_c<Fish*>, "");
  40. static_assert(animal_ptrs[1_c] == hana::type_c<Dog*>, "");
  41. // 2. Unroll loops at compile-time without hassle.
  42. std::string s;
  43. hana::int_c<10>.times([&]{ s += "x"; });
  44. // equivalent to s += "x"; s += "x"; ... s += "x";
  45. // 3. Easily check whether an expression is valid.
  46. // This is usually achieved with complex SFINAE-based tricks.
  47. auto has_name = hana::is_valid([](auto&& x) -> decltype((void)x.name) { });
  48. static_assert(has_name(animals[0_c]), "");
  49. static_assert(!has_name(1), "");
  50. }