using a typedefed variable with library classes
bearophile
bearophileHUGS at lycos.com
Sat Jan 10 17:16:34 PST 2009
Bill Baxter:
> I've never found a use for typedef myself. I don't think it's used much,<
In Pascal (and its variant and children, like ObjectPascals, etc) there is a section named Type where you define your typedefs. People used to program in Pascal-like languages (ObjectPascals, Ada, Oberon, etc) may appreciate the typedef of D and they may use it.
I use typedef now and then, I presume it's mostly useful for imperative style of programming and not much in OOP.
A simple usage example: you have a procedural/functional program that has several functions that process a matrix, the same matrix, for example a float[12][7]. In such situation you may want to define:
typedef float[12][7] FPfield;
Then if you use FPField in function signatures like this:
void foo(FPfield mat, ...) { ... }
you gain some things:
- The type name may be shorter, saving you some typing. And you don't need to remember each time the size of the dimensions.
- If you later want to FPfield into a matrix of doubles or the matrix you have to change only one line. If your code uses a dynamic array this is less important. But from coding a lot of programs in D I have seen programs up to 2-5-10 times faster when I use 3D/4D static arrays, mostly because lot of address computations are done at compile time or partially optimized away instead of run time, and because of higher cache coherence. I can show an extreme example, if you want. D dynamic arrays can't replace all static arrays where speed matters.
- It's a way to document the code, because you aren't just giving a generic matrix to foo, you are giving it a FPfield, this often has an important semantic meaning.
- It's type safe, so you don't risk giving the wrong matrix to foo. You can't do this well with an alias. This is more useful in largish programs.
If you use OOP or lot generic programming this becomes less important.
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list