Often used to shorten the name of complicated types, especially when some sort of template + container combination is used.
small ex: typedef Vector2<float> Vector2f;
Perhaps someone else can give a more detailed explanation.
You should always prefer typedef or using over #define. There are three main reasons that I can think of for this:
- #define replaces EVERYTHING. If you try to use a variable with that name it will be replaced, and weird things will start happening.
- #define isn't scoped. If you just want an alias for use within a function or class, a #define will ignore where you put it (though for a function, I guess you could follow it with a #undef).
- #defines aren't affected by their context, so you can't do things like create aliases for function pointers or template arguments.
Of course, sometimes a #define could be useful, but mostly in their form as macros.
The uses for typedef and using are not only for shortening the name of complicated types as @Ganado said, but are also used in templated code for relevant types that could change. For example:
// A templated structure of some kind.
template <typename T>
struct A {
using type = T;
void doSomething(T t) {
// do something with t here
}
};
// A function which has received an instance of something, possibly
// the above structure, but doesn't know which template and hence
// what type to pass to its 'doSomething' member:
template <typename T>
void func(T& t) {
T::type val;
// calculate and do thing's with val in some way
t.doSomething(val);
}
// ... possible use (in some function somewhere):
A<int> a;
func(a); // In func, 'val' will be of type 'int'.