function.qbk 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. [/==============================================================================
  2. Copyright (C) 2001-2010 Joel de Guzman
  3. Copyright (C) 2001-2005 Dan Marsden
  4. Copyright (C) 2001-2010 Thomas Heller
  5. Distributed under the Boost Software License, Version 1.0. (See accompanying
  6. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. ===============================================================================/]
  8. [section Lazy Functions]
  9. As you write more lambda functions, you'll notice certain patterns that you wish
  10. to refactor as reusable functions. When you reach that point, you'll wish that
  11. ordinary functions can co-exist with phoenix functions. Unfortunately, the
  12. /immediate/ nature of plain C++ functions make them incompatible.
  13. Lazy functions are your friends. The library provides a facility to make lazy
  14. functions. The code below is a rewrite of the `is_odd` function using the
  15. facility:
  16. struct is_odd_impl
  17. {
  18. typedef bool result_type;
  19. template <typename Arg>
  20. bool operator()(Arg arg1) const
  21. {
  22. return arg1 % 2 == 1;
  23. }
  24. };
  25. function<is_odd_impl> is_odd;
  26. [heading Things to note:]
  27. [/
  28. * `result` is a nested metafunction that reflects the return type of the
  29. function (in this case, bool). This makes the function fully polymorphic:
  30. It can work with arbitrary `Arg` types.
  31. * There are as many Args in the `result` metafunction as in the actual
  32. `operator()`.
  33. ]
  34. * Result type deduction is implemented with the help of the result_of protocol.
  35. For more information see __boost_result_of__
  36. * `is_odd_impl` implements the function.
  37. * `is_odd`, an instance of `function<is_odd_impl>`, is the lazy function.
  38. Now, `is_odd` is a truly lazy function that we can use in conjunction with the
  39. rest of phoenix. Example:
  40. std::find_if(c.begin(), c.end(), is_odd(arg1));
  41. (See [@../../example/function.cpp function.cpp])
  42. [heading Predefined Lazy Functions]
  43. The library is chock full of STL savvy, predefined lazy functions covering the
  44. whole of the STL containers, iterators and algorithms. For example, there are lazy
  45. versions of container related operations such as assign, at, back, begin,
  46. pop_back, pop_front, push_back, push_front, etc. (See [link phoenix.modules.stl
  47. STL]).
  48. [endsect]