Suggestion: shortcut for 'new X'

Kristian kjkilpi at gmail.com
Fri Aug 25 02:30:37 PDT 2006


On Fri, 25 Aug 2006 11:38:18 +0300, Rémy J. A. Mouëza  
<ray.jay.ay.moueza at do.not.spam.gmail.com> wrote:

>
>>> Kristian wrote:
>>> Consider the following:
>>>
>>> Obj func2() {...}
>>>
>>> void func() {
>>>      auto obj = func2();
>>> }
>
> For such cases, there is the typeof() operator :
>
> Obj func2 () { ... }
>
> void func ()
> {	typeof ( func2 ) obj = func2 ();
> }
>
> And one knows exactly that obj's type is the same as func2 return type,  
> and there is no mistake possible with an auto type, althought it becomes
> redundant.
> It does not matter that much in a dynamically typed language :
>
> def func2 (): return Something ()
>
> def func ():
>      obj = func2 ()
>
> It seems that there will always be some redundancy in a typed language à  
> la C, nonetheless D has made great improvement.

Well yes, but you missed my point though.

void func() {
     auto obj1 = func2();
     typeof(func2) obj2 = func2();
}

You (or someone reading the code, lets say, a year later) know that the  
type of both 'obj1' and 'obj2' are the same as the type of 'func2()'. But  
you don't know the type of 'func2()' without looking at the definion of  
'func2()' or at the docs.

Someone may argue that declaring 'Obj' in "auto obj1 = func2();" is  
redundant because 'func2()' returns 'Obj'. But that information is not  
apparent to you when you look at 'func()'. So it's not redundant code  
inside 'func()'. If you like to use 'obj1', then you have to know its  
type, of course. It's good programming style to declare the type for  
'obj1' or you may end up with code that nobody knows the types of objects  
without looking at the documention/function declarations all the time. It  
would be very painful to modify the code later, even if you do it by  
yourself.



More information about the Digitalmars-d mailing list