Is typedef an alien?

Steven Schveighoffer schveiguy at yahoo.com
Thu Sep 24 12:15:12 PDT 2009


On Thu, 24 Sep 2009 14:36:01 -0400, Aenigmatic <procode at adam-dott-com.au>  
wrote:

> No further response to any responses to my previous post's responses is  
> a both swift and non-invasive.
>
> Now my deeply thought question is ...
>
> Is typedef (in D) a C/C++ legacy or is the dear orphan now adopted as a  
> first-class citizen in the US of D?
>
> -- Yours truly, Justin Johansson

typedef is different from alias -- but has some issues.

typedef creates a new *incompatible* type.  By incompatible, I mean that  
it doesn't implicitly cast back to the type you created it from.

e.g.:

typedef int mytype;

mytype x;

int y = x; // ok, mytype implicitly casts to x

x = y; // error, can't implicitly cast.

typedef is a distinct type, so it can be used to overload a function:

foo(mytype m);
foo(int i);

mytype x;
foo(x); // calls foo(mytype) version

You can also set the default value different from the original type:

typedef int mytype=5;

mytype x; // set to 5.

However, there are issues, such as operations don't "just work."

i.e.:

mytype x = 5;

mytype y = x + 5; // error, x + 5 results in an int!  Need a cast

My experience is that 99% of the time, alias is what you want.  I haven't  
yet encountered a good case for using typedef.

But it's abilities certainly are not covered by any other construct, so  
I'd say it's a first class citizen.

-Steve



More information about the Digitalmars-d mailing list