File: referencewrappers.yo

package info (click to toggle)
c%2B%2B-annotations 13.02.02-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,576 kB
  • sloc: cpp: 25,297; makefile: 1,523; ansic: 165; sh: 126; perl: 90; fortran: 27
file content (34 lines) | stat: -rw-r--r-- 1,933 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Before using the reference wrappers discussed in this section the
tthi(functional) header file must be included.

Situations exist where the compiler is unable to infer that a reference rather
than a value is passed to a function template. In the following example the
function template  tt(outer) receives tt(int x) as its argument and the
compiler dutifully infers that tt(Type) is tt(int):
        verbinclude(//INT examples/refwrap.cc)
    Compilation will of course fail (as tt(int) values don't have tt(x)
members) and the compiler nicely reports the inferred type, e.g.:
        verb(    In function 'void outer(Type) [with Type = int]': ...)

Another type of error results from using tt(call) in the next example. Here,
tt(call) is a function template expecting a function-type argument. The
function that's passed to tt(call) is tt(sqrtArg), defining a reference to a
tt(double): the variable that's passed to tt(sqrtArg) is modified by
tt(sqrtArg). 
        verbinclude(//DOUBLE examples/refwrap.cc)
    The first time tt(call) is used, tt(call(sqrtArg, value)) will not modify
tt(value): the compiler infers tt(Arg) to be a tt(double) value, and hence
passes tt(value) by value to tt(call), thus preventing tt(sqrtArg) to modify
tt(main's) variable.

    To change tt(main's) variable tt(value) the compiler must be informed that
tt(value) must be passed by reference. Note that we do not want to 
define tt(call)'s template parameter as a reference parameter, 
as passing arguments by value might be appropriate in other situations.

    In these situations the ti(CHAR(r)ef(arg)) and ti(cref(arg))
 hi(reference wrapper)em(reference wrappers) should be used. They accept an
argument and return their argument as a (const) reference-typed argument. To
actually change tt(value) it can be passed to tt(call) using tt(ref(value)) as
shown in the following tt(main) function:
        verbinclude(//MAIN examples/refwrap.cc)