bind_function_object_tests_phx2.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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/bind.hpp>
  12. using namespace boost::phoenix;
  13. using namespace boost::phoenix::arg_names;
  14. using namespace std;
  15. struct test
  16. {
  17. typedef void result_type;
  18. void operator()() const
  19. {
  20. cout << "Test lazy functions...\n";
  21. }
  22. };
  23. struct sqr
  24. {
  25. template <typename Arg>
  26. struct result
  27. {
  28. typedef Arg type;
  29. };
  30. template <typename Arg>
  31. Arg operator()(Arg n) const
  32. {
  33. return n * n;
  34. }
  35. };
  36. struct fact
  37. {
  38. template <typename Arg>
  39. struct result
  40. {
  41. typedef Arg type;
  42. };
  43. template <typename Arg>
  44. Arg operator()(Arg n) const
  45. {
  46. return (n <= 0) ? 1 : n * (*this)(n-1);
  47. }
  48. };
  49. struct power
  50. {
  51. template <typename Arg1, typename Arg2>
  52. struct result
  53. {
  54. typedef Arg1 type;
  55. };
  56. template <typename Arg1, typename Arg2>
  57. Arg1 operator()(Arg1 a, Arg2 b) const
  58. {
  59. return pow(a, b);
  60. }
  61. };
  62. struct add
  63. {
  64. template <typename Arg1, typename Arg2, typename Arg3, typename Arg4>
  65. struct result
  66. {
  67. typedef Arg1 type;
  68. };
  69. template <typename Arg1, typename Arg2, typename Arg3, typename Arg4>
  70. Arg1 operator()(Arg1 a, Arg2 b, Arg3 c, Arg4 d) const
  71. {
  72. return a + b + c + d;
  73. }
  74. };
  75. int
  76. main()
  77. {
  78. int i5 = 5;
  79. double d5 = 5, d3 = 3;
  80. test()();
  81. BOOST_TEST(bind(sqr(), arg1)(i5) == (i5*i5));
  82. BOOST_TEST(bind(fact(), 4)() == 24);
  83. BOOST_TEST(bind(fact(), arg1)(i5) == 120);
  84. BOOST_TEST((int)bind(power(), arg1, arg2)(d5, d3) == (int)pow(d5, d3));
  85. BOOST_TEST((bind(sqr(), arg1) + 5)(i5) == ((i5*i5)+5));
  86. BOOST_TEST(bind(add(), arg1, arg1, arg1, arg1)(i5) == (5+5+5+5));
  87. int const ic5 = 5;
  88. // testing consts
  89. BOOST_TEST(bind(sqr(), arg1)(ic5) == (ic5*ic5));
  90. // From Steven Watanabe
  91. sqr s;
  92. int x = 2;
  93. int result = bind(ref(s), _1)(x);
  94. BOOST_TEST(result == 4);
  95. return boost::report_errors();
  96. }