typedef: what's it good for?

Simen Kjaeraas simen.kjaras at gmail.com
Wed Nov 11 05:11:44 PST 2009


On Wed, 11 Nov 2009 07:45:26 +0100, BCS <none at anon.com> wrote:

> Hello Walter,
>
>> When I originally worked out ideas for D, there were many requests
>> from the C and C++ community for a 'strong' typedef, and so I put one
>> in D. I didn't think about it too much, just assumed that it was a
>> good idea.
>>  Now I'm not so sure. Maybe it should be removed for D2.
>>  Does anyone use typedef's?
>>  What do you use them for?
>>  Do you need them?
>>
>
> I'd use them more if they were stronger. particularly, I'd love it if  
> they could be used to add/overide stuff basic types:
>
> typedef int TD
> {
>    TD opAdd(TD that) { assert(this < that); return cast(int)this +  
> cast(int)that; }
>    ...
> }
>
> or even better
>
> typedef int TD(T)
> {
>    TD!(T) opAdd(TD!(T) that) if (Pred!(T)) = default; // use the default  
> but restrict the operation
>    ...
> }
>
>

We can already do that in D2:

struct myInt {
     int _payload;
     alias _payload this;

     myInt opAdd( myInt that ) {
         assert( this._payload < that._payload );
         return this._payload + that.payload;
     }
}

And I would believe this is why removing typedef is now being discussed.
I like typedefs for when I need a separate type with no bells and
whistles, and so suggest that

     typedef int foo;

be kept as it is, and

     typedef int bar {
         /* stuffs */
     }

be sugar for

     struct bar {
         int _payload;
         alias _payload this;
         /* stuffs */
     }

--
Simen



More information about the Digitalmars-d mailing list