sample6.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*=============================================================================
  2. Phoenix V1.2.1
  3. Copyright (c) 2001-2003 Joel de Guzman
  4. Use, modification and distribution is subject to the Boost Software
  5. License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  6. http://www.boost.org/LICENSE_1_0.txt)
  7. ==============================================================================*/
  8. #include <vector>
  9. #include <algorithm>
  10. #include <iostream>
  11. #include <boost/spirit/include/phoenix1_operators.hpp>
  12. #include <boost/spirit/include/phoenix1_primitives.hpp>
  13. #include <boost/spirit/include/phoenix1_composite.hpp>
  14. #include <boost/spirit/include/phoenix1_special_ops.hpp>
  15. using namespace std;
  16. using namespace phoenix;
  17. //////////////////////////////////
  18. template <typename CondT, typename TrueT, typename FalseT>
  19. struct if_else_composite {
  20. typedef if_else_composite<CondT, TrueT, FalseT> self_t;
  21. template <typename TupleT>
  22. struct result {
  23. typedef typename higher_rank<
  24. typename actor_result<TrueT, TupleT>::plain_type,
  25. typename actor_result<FalseT, TupleT>::plain_type
  26. >::type type;
  27. };
  28. if_else_composite(
  29. CondT const& cond_, TrueT const& true__, FalseT const& false__)
  30. : cond(cond_), true_(true__), false_(false__) {}
  31. template <typename TupleT>
  32. typename actor_result<self_t, TupleT>::type
  33. eval(TupleT const& args) const
  34. {
  35. return cond.eval(args) ? true_.eval(args) : false_.eval(args);
  36. }
  37. CondT cond; TrueT true_; FalseT false_; // actors
  38. };
  39. //////////////////////////////////
  40. template <typename CondT, typename TrueT, typename FalseT>
  41. inline actor<if_else_composite<
  42. typename as_actor<CondT>::type,
  43. typename as_actor<TrueT>::type,
  44. typename as_actor<FalseT>::type> >
  45. if_else_(CondT const& cond, TrueT const& true_, FalseT const& false_)
  46. {
  47. typedef if_else_composite<
  48. typename as_actor<CondT>::type,
  49. typename as_actor<TrueT>::type,
  50. typename as_actor<FalseT>::type>
  51. result;
  52. return result(
  53. as_actor<CondT>::convert(cond),
  54. as_actor<TrueT>::convert(true_),
  55. as_actor<FalseT>::convert(false_));
  56. }
  57. //////////////////////////////////
  58. int
  59. main()
  60. {
  61. int init[] = { 2, 10, 4, 5, 1, 6, 8, 3, 9, 7 };
  62. vector<int> c(init, init + 10);
  63. typedef vector<int>::iterator iterator;
  64. // Print all contents of an stl container c and
  65. // prefix " is odd" or " is even" appropriately.
  66. for_each(c.begin(), c.end(),
  67. cout
  68. << arg1
  69. << if_else_(arg1 % 2 == 1, " is odd", " is even")
  70. << val('\n')
  71. );
  72. return 0;
  73. }