struct.mcd.tag_dispatching.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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/assert.hpp>
  5. #include <boost/hana/config.hpp>
  6. #include <boost/hana/core/to.hpp>
  7. #include <boost/hana/equal.hpp>
  8. #include <boost/hana/find.hpp>
  9. #include <boost/hana/functional/id.hpp>
  10. #include <boost/hana/fwd/accessors.hpp>
  11. #include <boost/hana/integral_constant.hpp>
  12. #include <boost/hana/not_equal.hpp>
  13. #include <boost/hana/pair.hpp>
  14. #include <boost/hana/string.hpp>
  15. #include <boost/hana/tuple.hpp>
  16. #include <string>
  17. #include <utility>
  18. namespace hana = boost::hana;
  19. //! [main]
  20. struct Person {
  21. std::string name;
  22. int age;
  23. };
  24. // The keys can be anything as long as they are compile-time comparable.
  25. constexpr auto name = hana::integral_c<std::string Person::*, &Person::name>;
  26. constexpr auto age = hana::string_c<'a', 'g', 'e'>;
  27. namespace boost { namespace hana {
  28. template <>
  29. struct accessors_impl<Person> {
  30. static BOOST_HANA_CONSTEXPR_LAMBDA auto apply() {
  31. return make_tuple(
  32. make_pair(name, [](auto&& p) -> decltype(auto) {
  33. return id(std::forward<decltype(p)>(p).name);
  34. }),
  35. make_pair(age, [](auto&& p) -> decltype(auto) {
  36. return id(std::forward<decltype(p)>(p).age);
  37. })
  38. );
  39. }
  40. };
  41. }}
  42. //! [main]
  43. int main() {
  44. Person john{"John", 30}, bob{"Bob", 40};
  45. BOOST_HANA_RUNTIME_CHECK(hana::equal(john, john));
  46. BOOST_HANA_RUNTIME_CHECK(hana::not_equal(john, bob));
  47. BOOST_HANA_RUNTIME_CHECK(hana::find(john, name) == hana::just("John"));
  48. BOOST_HANA_RUNTIME_CHECK(hana::find(john, age) == hana::just(30));
  49. BOOST_HANA_CONSTANT_CHECK(hana::find(john, BOOST_HANA_STRING("foo")) == hana::nothing);
  50. BOOST_HANA_RUNTIME_CHECK(hana::to_tuple(john) == hana::make_tuple(
  51. hana::make_pair(name, "John"),
  52. hana::make_pair(age, 30)
  53. ));
  54. }