values.qbk 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 Values]
  9. Values are functions! Examples:
  10. val(3)
  11. val("Hello, World")
  12. The first evaluates to a nullary function (a function taking no arguments) that
  13. returns an `int`, `3`. The second evaluates to a nullary function that returns
  14. a `char const(&)[13]`, `"Hello, World"`.
  15. [heading Lazy Evaluation]
  16. Confused? `val` is a unary function and `val(3)` invokes it, you say?
  17. Yes. However, read carefully: /"evaluates to a nullary function"/.
  18. `val(3)` evaluates to (returns) a nullary function. Aha! `val(3)`
  19. returns a function! So, since `val(3)` returns a function, you can
  20. invoke it. Example:
  21. std::cout << val(3)() << std::endl;
  22. (See [@../../example/values.cpp values.cpp])
  23. [blurb __tip__ Learn more about values [link phoenix.modules.core.values here.]]
  24. The second function call (the one with no arguments) calls the nullary function
  25. which then returns `3`. The need for a second function call is the reason why
  26. the function is said to be [*/Lazily Evaluated/]. The first call doesn't do
  27. anything. You need a second call to finally evaluate the thing. The first call
  28. lazily evaluates the function; i.e. doesn't do anything and defers the evaluation
  29. for later.
  30. [heading Callbacks]
  31. It may not be immediately apparent how lazy evaluation can be useful by just
  32. looking at the example above. Putting the first and second function call in a
  33. single line is really not very useful. However, thinking of `val(3)` as a
  34. callback function (and in most cases they are actually used that way), will make
  35. it clear. Example:
  36. template <typename F>
  37. void print(F f)
  38. {
  39. cout << f() << endl;
  40. }
  41. int
  42. main()
  43. {
  44. print(val(3));
  45. print(val("Hello World"));
  46. return 0;
  47. }
  48. (See [@../../example/callback.cpp callback.cpp])
  49. [endsect]