Suggestion: Change precedence of 'new'

Bill Baxter dnewsgroup at billbaxter.com
Fri Apr 11 13:35:42 PDT 2008


Simen Kjaeraas wrote:
> On Thu, 10 Apr 2008 03:32:01 +0200, Bill Baxter 
> <dnewsgroup at billbaxter.com> wrote:
> 
>> Sometimes it's handy to invoke a function on a class right after 
>> creating it:
>>
>>      new Thread(&func).run();
>>
>> Unfortunately that doesn't work in D right now.  You have to put 
>> parentheses around the new expression because it has lower precedence 
>> than dotExpression:
>>
>>       (new Thread(&func)).run();
>>
>> I don't recall how it works in C++, but at least in Java, the first 
>> version works.
>>
>> I'm not a grammar guru, so can anyone who is say whether the above 
>> change would be possible?
>>
>> Maybe it would muck up construction based on fully qualified names?   
>> So that
>>
>>    new thread.Thread(&func)
>>
>> would have to become
>>
>>    new (thread.Thread(&func)
>>
>> If so that would suck.  But Java is able to make it work somehow, and 
>> the construct seems to be used quite heavily there (I've been looking 
>> at a lot of SWT code lately...)
>>
>> --bb
> 
> 
> You can work around this with static opCalls.
> 
> class foo
> {
>     static foo opCall()
>     {
>         return new foo();
>     }
> 
>     int bar()
>     {
>       return 4;
>     }
> }
> 
> 
> int a = foo().bar;
> 
> Still requires a parentheses, but you might like it better.


No.  I'm not going to start writing constructors for every class twice 
just to be able to save on some parenthesis in certain situations.  If 
making "new foo().bar" work is going to have any undesirable side 
effects than it's not worth it.  It just seemed to me that it might be a 
simple change to the grammar.

--bb



More information about the Digitalmars-d mailing list