at_key.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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/at_key.hpp>
  6. #include <boost/hana/define_struct.hpp>
  7. #include <boost/hana/string.hpp>
  8. #include <string>
  9. namespace hana = boost::hana;
  10. struct Person {
  11. BOOST_HANA_DEFINE_STRUCT(Person,
  12. (std::string, name),
  13. (std::string, last_name),
  14. (int, age)
  15. );
  16. };
  17. int main() {
  18. // non-const ref
  19. {
  20. Person john{"John", "Doe", 30};
  21. std::string& name = hana::at_key(john, BOOST_HANA_STRING("name"));
  22. std::string& last_name = hana::at_key(john, BOOST_HANA_STRING("last_name"));
  23. int& age = hana::at_key(john, BOOST_HANA_STRING("age"));
  24. name = "Bob";
  25. last_name = "Foo";
  26. age = 99;
  27. BOOST_HANA_RUNTIME_CHECK(john.name == "Bob");
  28. BOOST_HANA_RUNTIME_CHECK(john.last_name == "Foo");
  29. BOOST_HANA_RUNTIME_CHECK(john.age == 99);
  30. }
  31. // const ref
  32. {
  33. Person john{"John", "Doe", 30};
  34. Person const& const_john = john;
  35. std::string const& name = hana::at_key(const_john, BOOST_HANA_STRING("name"));
  36. std::string const& last_name = hana::at_key(const_john, BOOST_HANA_STRING("last_name"));
  37. int const& age = hana::at_key(const_john, BOOST_HANA_STRING("age"));
  38. john.name = "Bob";
  39. john.last_name = "Foo";
  40. john.age = 99;
  41. BOOST_HANA_RUNTIME_CHECK(name == "Bob");
  42. BOOST_HANA_RUNTIME_CHECK(last_name == "Foo");
  43. BOOST_HANA_RUNTIME_CHECK(age == 99);
  44. }
  45. }