• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1[/==============================================================================
2    Copyright (C) 2001-2010 Joel de Guzman
3    Copyright (C) 2001-2005 Dan Marsden
4    Copyright (C) 2001-2010 Thomas Heller
5
6    Distributed under the Boost Software License, Version 1.0. (See accompanying
7    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8===============================================================================/]
9
10[section Values]
11
12Values are functions! Examples:
13
14    val(3)
15    val("Hello, World")
16
17The first evaluates to a nullary function (a function taking no arguments) that
18returns an `int`, `3`. The second evaluates to a nullary function that returns
19a `char const(&)[13]`, `"Hello, World"`.
20
21[heading Lazy Evaluation]
22
23Confused? `val` is a unary function and `val(3)` invokes it, you say?
24Yes. However, read carefully: /"evaluates to a nullary function"/.
25`val(3)` evaluates to (returns) a nullary function. Aha! `val(3)`
26returns a function! So, since `val(3)` returns a function, you can
27invoke it. Example:
28
29    std::cout << val(3)() << std::endl;
30
31(See [@../../example/values.cpp values.cpp])
32
33[blurb __tip__ Learn more about values [link phoenix.modules.core.values here.]]
34
35The second function call (the one with no arguments) calls the nullary function
36which then returns `3`. The need for a second function call is the reason why
37the function is said to be [*/Lazily Evaluated/]. The first call doesn't do
38anything. You need a second call to finally evaluate the thing. The first call
39lazily evaluates the function; i.e. doesn't do anything and defers the evaluation
40for later.
41
42[heading Callbacks]
43
44It may not be immediately apparent how lazy evaluation can be useful by just
45looking at the example above. Putting the first and second function call in a
46single line is really not very useful. However, thinking of `val(3)` as a
47callback function (and in most cases they are actually used that way), will make
48it clear. Example:
49
50    template <typename F>
51    void print(F f)
52    {
53        cout << f() << endl;
54    }
55
56    int
57    main()
58    {
59        print(val(3));
60        print(val("Hello World"));
61        return 0;
62    }
63
64(See [@../../example/callback.cpp callback.cpp])
65
66[endsect]
67
68