function_tests_phx2.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. /*=============================================================================
  2. Copyright (c) 2001-2007 Joel de Guzman
  3. Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. ==============================================================================*/
  6. #include <iostream>
  7. #include <cmath>
  8. #include <boost/detail/lightweight_test.hpp>
  9. #include <boost/phoenix/core.hpp>
  10. #include <boost/phoenix/operator.hpp>
  11. #include <boost/phoenix/function.hpp>
  12. using namespace boost::phoenix;
  13. using namespace boost::phoenix::arg_names;
  14. using namespace std;
  15. struct test_impl
  16. {
  17. typedef void result_type;
  18. void operator()() const
  19. {
  20. cout << "Test lazy functions...\n";
  21. }
  22. };
  23. function<test_impl> test;
  24. struct sqr_impl
  25. {
  26. template <typename Arg>
  27. struct result
  28. {
  29. typedef Arg type;
  30. };
  31. template <typename Arg>
  32. Arg operator()(Arg n) const
  33. {
  34. return n * n;
  35. }
  36. };
  37. function<sqr_impl> sqr;
  38. struct fact_impl
  39. {
  40. template <typename Arg>
  41. struct result
  42. {
  43. typedef Arg type;
  44. };
  45. template <typename Arg>
  46. Arg operator()(Arg n) const
  47. {
  48. return (n <= 0) ? 1 : n * (*this)(n-1);
  49. }
  50. };
  51. function<fact_impl> fact;
  52. struct pow_impl
  53. {
  54. template <typename Arg1, typename Arg2>
  55. struct result
  56. {
  57. typedef Arg1 type;
  58. };
  59. template <typename Arg1, typename Arg2>
  60. Arg1 operator()(Arg1 a, Arg2 b) const
  61. {
  62. return pow(a, b);
  63. }
  64. };
  65. function<pow_impl> power;
  66. struct add_impl
  67. {
  68. template <typename Arg1, typename Arg2, typename Arg3, typename Arg4>
  69. struct result
  70. {
  71. typedef Arg1 type;
  72. };
  73. template <typename Arg1, typename Arg2, typename Arg3, typename Arg4>
  74. Arg1 operator()(Arg1 a, Arg2 b, Arg3 c, Arg4 d) const
  75. {
  76. return a + b + c + d;
  77. }
  78. };
  79. function<add_impl> add;
  80. int
  81. main()
  82. {
  83. int i5 = 5;
  84. double d5 = 5, d3 = 3;
  85. test()();
  86. BOOST_TEST(sqr(arg1)(i5) == (i5*i5));
  87. BOOST_TEST(fact(4)() == 24);
  88. BOOST_TEST(fact(arg1)(i5) == 120);
  89. BOOST_TEST((int)power(arg1, arg2)(d5, d3) == (int)pow(d5, d3));
  90. BOOST_TEST((sqr(arg1) + 5)(i5) == ((i5*i5)+5));
  91. BOOST_TEST(add(arg1, arg1, arg1, arg1)(i5) == (5+5+5+5));
  92. int const ic5 = 5;
  93. // testing consts
  94. BOOST_TEST(sqr(arg1)(ic5) == (ic5*ic5));
  95. return boost::report_errors();
  96. }