On Sun, Jan 11, 2009 at 10:16 AM, bearophile <bearophileh...@lycos.com> wrote: > 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.
Actually it might be useful to me. The first time I tried to use it my thought was to do typedef Exception MyException; To create a different exception type. That doesn't work so I kinda just said, eh whatever, this typedef stuff doesn't work yet. But probably that's just because that's not the use case they were intended for. Something I might be able to use it for is for index types. Like this: typedef size_t VertexHandle; typedef size_t FaceHandle; Now I can't accidentally assign a vertex handle to a face handle. That could be useful. --bb