applicative.complex.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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/ap.hpp>
  5. #include <boost/hana/assert.hpp>
  6. #include <boost/hana/bool.hpp>
  7. #include <boost/hana/config.hpp>
  8. #include <boost/hana/equal.hpp>
  9. #include <boost/hana/if.hpp>
  10. #include <boost/hana/lift.hpp>
  11. #include <boost/hana/optional.hpp>
  12. namespace hana = boost::hana;
  13. template <char op>
  14. constexpr auto function = hana::nothing;
  15. template <>
  16. BOOST_HANA_CONSTEXPR_LAMBDA auto function<'+'> = hana::just([](auto x, auto y) {
  17. return x + y;
  18. });
  19. template <>
  20. BOOST_HANA_CONSTEXPR_LAMBDA auto function<'-'> = hana::just([](auto x, auto y) {
  21. return x - y;
  22. });
  23. // and so on...
  24. template <char n>
  25. constexpr auto digit = hana::if_(hana::bool_c<(n >= '0' && n <= '9')>,
  26. hana::just(static_cast<int>(n - 48)),
  27. hana::nothing
  28. );
  29. template <char x, char op, char y>
  30. BOOST_HANA_CONSTEXPR_LAMBDA auto evaluate = hana::ap(function<op>, digit<x>, digit<y>);
  31. int main() {
  32. BOOST_HANA_CONSTEXPR_CHECK(evaluate<'1', '+', '2'> == hana::just(1 + 2));
  33. BOOST_HANA_CONSTEXPR_CHECK(evaluate<'4', '-', '2'> == hana::just(4 - 2));
  34. BOOST_HANA_CONSTANT_CHECK(evaluate<'?', '+', '2'> == hana::nothing);
  35. BOOST_HANA_CONSTANT_CHECK(evaluate<'1', '?', '2'> == hana::nothing);
  36. BOOST_HANA_CONSTANT_CHECK(evaluate<'1', '+', '?'> == hana::nothing);
  37. BOOST_HANA_CONSTANT_CHECK(evaluate<'?', '?', '?'> == hana::nothing);
  38. static_assert(hana::lift<hana::optional_tag>(123) == hana::just(123), "");
  39. }