The trick I've found with typedefs is to first ignore the typedef
keyword and look at the other bits; so
int value_type;
would declare a variable called value_type
of type int
. Add the typedef
keyword, and it's exactly the same, but rather than declaring a new variable, you're declaring a new type that's an int
.
I find this helpful in more complex cases like
typedef int (*Func)(float, double);
Remove typedef
and you're declaring a function called *Func
which takes two parameters and returns an int. Add the keyword back in, and you're declaring a function type with that signature.
EDIT:
From comments on other answers, it seems like it's not so much the typedef itself but std::size_t
that's giving you bother.
std::size_t
is itself the name of a standard library type, specifically, the type of the number returned by the built-in sizeof
operator. It's always an unsigned integer, but the exact type depends on the compiler and the system you're using (and even particular compiler options).
How do you know that std::size_t
is a type name, rather than a variable name? The short answer is that you often can't, you just have to judge by the name and the context (in fact, sometimes even the compiler doesn't even know whether a name refers to a type or whether it refers to a variable, so you have to tell it). In this case, the fact that it ends in _t
is a good clue that it's a type (plus the fact it's used in a typedef!).
The std
part refers to the std
namespace. Namespaces are a C++ facility (also present in other languages, though not C) for avoiding name clashes. You can declare your own, and std
is a special on reserved for the standard library.
The A::B
thing is called the scope resolution operator, and it tells the compiler "look inside A
for something named B
", where A
can be either class or a namespace.