at_key.stackoverflow.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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/fold_left.hpp>
  7. #include <boost/hana/integral_constant.hpp>
  8. #include <boost/hana/map.hpp>
  9. #include <boost/hana/pair.hpp>
  10. #include <boost/hana/range.hpp>
  11. namespace hana = boost::hana;
  12. //
  13. // Make sure that http://stackoverflow.com/q/32702383/627587 works.
  14. //
  15. auto at = [](auto& map, auto key) -> auto& {
  16. return map[key];
  17. };
  18. template <typename Map, typename Keys>
  19. auto& traverse(Map& map, Keys const& keys){
  20. return hana::fold_left(keys, map, at);
  21. }
  22. int main() {
  23. auto xs = hana::make_map(hana::make_pair(hana::int_c<0>,
  24. hana::make_map(hana::make_pair(hana::int_c<1>,
  25. hana::make_map(hana::make_pair(hana::int_c<2>,
  26. hana::make_map(hana::make_pair(hana::int_c<3>, 10))))))));
  27. int& i = traverse(xs, hana::range_c<int, 0, 4>);
  28. BOOST_HANA_RUNTIME_CHECK(i == 10);
  29. i = 99;
  30. BOOST_HANA_RUNTIME_CHECK(traverse(xs, hana::range_c<int, 0, 4>) == 99);
  31. }