if_else.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. // Copyright (C) 2016-2018 T. Zachary Laine
  2. //
  3. // Distributed under the Boost Software License, Version 1.0. (See
  4. // accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. #include <boost/yap/expression.hpp>
  7. #include <boost/test/minimal.hpp>
  8. #include <sstream>
  9. template<typename T>
  10. using term = boost::yap::terminal<boost::yap::expression, T>;
  11. template<typename T>
  12. using term_ref = boost::yap::expression_ref<boost::yap::expression, term<T> &>;
  13. template<typename T>
  14. using term_cref =
  15. boost::yap::expression_ref<boost::yap::expression, term<T> const &>;
  16. namespace yap = boost::yap;
  17. namespace bh = boost::hana;
  18. struct callable
  19. {
  20. int operator()() { return 42; }
  21. };
  22. struct side_effect_callable_1
  23. {
  24. int operator()()
  25. {
  26. *value_ = 1;
  27. return 0;
  28. }
  29. int * value_;
  30. };
  31. struct side_effect_callable_2
  32. {
  33. int operator()()
  34. {
  35. *value_ = 2;
  36. return 0;
  37. }
  38. int * value_;
  39. };
  40. int test_main(int, char * [])
  41. {
  42. {
  43. int one = 0;
  44. int two = 0;
  45. auto true_nothrow_throw_expr = if_else(
  46. term<bool>{{true}},
  47. term<callable>{}(),
  48. term<side_effect_callable_1>{{&one}}());
  49. BOOST_CHECK(yap::evaluate(true_nothrow_throw_expr) == 42);
  50. BOOST_CHECK(one == 0);
  51. BOOST_CHECK(two == 0);
  52. }
  53. {
  54. int one = 0;
  55. int two = 0;
  56. auto false_nothrow_throw_expr = if_else(
  57. term<bool>{{false}},
  58. term<callable>{}(),
  59. term<side_effect_callable_1>{{&one}}());
  60. BOOST_CHECK(yap::evaluate(false_nothrow_throw_expr) == 0);
  61. BOOST_CHECK(one == 1);
  62. BOOST_CHECK(two == 0);
  63. }
  64. {
  65. int one = 0;
  66. int two = 0;
  67. auto true_throw1_throw2_expr = if_else(
  68. term<bool>{{true}},
  69. term<side_effect_callable_1>{{&one}}(),
  70. term<side_effect_callable_2>{{&two}}());
  71. BOOST_CHECK(yap::evaluate(true_throw1_throw2_expr) == 0);
  72. BOOST_CHECK(one == 1);
  73. BOOST_CHECK(two == 0);
  74. }
  75. {
  76. int one = 0;
  77. int two = 0;
  78. auto false_throw1_throw2_expr = if_else(
  79. term<bool>{{false}},
  80. term<side_effect_callable_1>{{&one}}(),
  81. term<side_effect_callable_2>{{&two}}());
  82. BOOST_CHECK(yap::evaluate(false_throw1_throw2_expr) == 0);
  83. BOOST_CHECK(one == 0);
  84. BOOST_CHECK(two == 2);
  85. }
  86. return 0;
  87. }