while.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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/equal.hpp>
  6. #include <boost/hana/integral_constant.hpp>
  7. #include <boost/hana/less.hpp>
  8. #include <boost/hana/plus.hpp>
  9. #include <boost/hana/while.hpp>
  10. #include <vector>
  11. namespace hana = boost::hana;
  12. using namespace hana::literals;
  13. int main() {
  14. // while_ with a Constant condition (loop is unrolled at compile-time)
  15. {
  16. std::vector<int> ints;
  17. auto final_state = hana::while_(hana::less.than(10_c), 0_c, [&](auto i) {
  18. ints.push_back(i);
  19. return i + 1_c;
  20. });
  21. // The state is known at compile-time
  22. BOOST_HANA_CONSTANT_CHECK(final_state == 10_c);
  23. BOOST_HANA_RUNTIME_CHECK(ints == std::vector<int>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
  24. }
  25. // while_ with a constexpr or runtime condition (loop is not unrolled)
  26. {
  27. std::vector<int> ints;
  28. int final_state = hana::while_(hana::less.than(10), 0, [&](int i) {
  29. ints.push_back(i);
  30. return i + 1;
  31. });
  32. // The state is known only at runtime, or at compile-time if constexpr
  33. BOOST_HANA_RUNTIME_CHECK(final_state == 10);
  34. BOOST_HANA_RUNTIME_CHECK(ints == std::vector<int>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
  35. }
  36. }