1
In bf(C++) tt(typedef) is commonly used to define shorthand notations for
2
complex types. Assume we want to define a shorthand for `a pointer to a
3
function expecting a double and an int, and returning an unsigned long long
4
int'. Such a function could be:
6
unsigned long long int compute(double, int);
8
A pointer to such a function has the following form:
10
unsigned long long int (*pf)(double, int);
12
If this kind of pointer is frequently used, consider defining it using
13
tt(typedef): simply put tt(typedef) in front of it and the pointer's name is
14
turned into the name of a type. It could be capitalized to let it stand out
15
more clearly as the name of a type:
17
typedef unsigned long long int (*PF)(double, int);
19
After having defined this type, it can be used to declare or define such
22
PF pf = compute; // initialize the pointer to a function like
24
void fun(PF pf); // fun expects a pointer to a function like
27
However, including the pointer in the typedef might not be a very good
28
idea, as it masks the fact that tt(pf) is a pointer. After all, tt(PF pf)
29
looks more like `tt(int x)' than `tt(int *x)'. To document that tt(pf) is
30
in fact a pointer, slightly change the tt(typedef):
32
typedef unsigned long long int FUN(double, int);
34
FUN *pf = compute; // now pf clearly is a pointer.
36
The scope of typedefs is restricted to compilation units. Therefore,
37
typedefs are usually embedded in header files which are then included by
38
multiple source files in which the typedefs should be used.
40
In addition to tt(typedef) the C++11 standard offers the ti(using) keyword to
41
associate a type and and identifier. In practice tt(typedef) and tt(using) can
42
be used interchangeably. The tt(using) keyword arguably result in more
43
readable type definitions. Consider the following three (equivalent)
46
it() The traditional, bf(C) style definition of a type, embedding the type
47
name in the definition (turning a variable name into a type name):
49
typedef typedef unsigned long long int FUN(double, int);
51
it() Apply tt(using) to improve the visibility (for humans) of the type
52
name, by moving the type name to the front of the definition:
54
using FUN = unsigned long long int (double, int);
56
it() An alternative construction, using a late-specified return type
57
(cf. section ref(AUTO)):
59
using FUN = auto (double, int) -> unsigned long long int;