Just wondering if anyone has solid advice on when and how to use typedef.
Just wondering if anyone has solid advice on when and how to use typedef.
Use typedef to give a long and difficult type an alias.
It is better to assume that there is no advantage at all, and only use typedef if writing out a variable's type is very fugly looking or especially error prone.Code:typedef std::map< int, vector<string> > StrIntMap; typedef int(*compare)(void *a, void *b) CompFn;
Last edited by whiteflags; 10-19-2006 at 11:14 AM.
>> writing out a variable's type is very fugly looking or especially error prone.
That is the advantage.
Use it when you gain a lot more in terms of clarity than you lose with the loss of detail in the code.
Function pointers are notoriously hard to get right, and exceedingly verbose if you have several parameters. This is usually a good idea to typedef these.
For a given T, using a typedef for T*
Eg. typedef int *intp;
You haven't saved any typing, you may as well type a * before something as type a 'p' after it. But you have made the code a hell of a lot harder to trace through since the number of *'s you use on the usage no longer agrees with the number of *'s on the declaration.
This is a bad use of typedef.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Excellent! Thank you... I had never really understood this. I already have several uses for this.
If you write any class which you want to be usable like an STL container, you'll need to typedef things like iterators and the like.
Also, citizen, I think your function pointer typedef should just be:
Code:typedef int(*CompFn)(void *a, void *b);
You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.