Casting by assigning to the right ...

12345swordy alexanderheistermann at gmail.com
Wed Apr 15 00:07:54 UTC 2020


On Tuesday, 14 April 2020 at 12:28:00 UTC, Steven Schveighoffer 
wrote:
> On 4/14/20 2:44 AM, Manfred Nowak wrote:
>> On Tuesday, 14 April 2020 at 06:10:33 UTC, Steven 
>> Schveighoffer wrote:
>>> Note that at this time, only one alias this is allowed per 
>>> structure.
>> 
>> This restriction falls by the suggested scheme:
>> 
>> ```
>> struct S{
>>    string data;
>>      import std.conv: to;
>>    void castTo( ref int arg){
>>      arg= to!int( data);
>>    }
>>    void castTo( ref string arg){
>>      arg= data;
>>    }
>> }
>> void main(){
>>    auto s= S( "42");
>> 
>>    int i;
>>    s.castTo =i;
>> 
>>    string str;
>>    s.castTo =str;
>> 
>>      import std.stdio;
>>    writeln( i, ":", str); // 42:42
>> }
>> ```
>
> Yes, I was responding to the point talking about 
> opImplicitCast. Instead of that, we got alias this.
>
> Proposals have been started to add multiple alias this. I think 
> many consider alias this in general to be a troublesome feature 
> that could have been done better. I don't know what will happen 
> with it.
>
> I would recommend not using the = syntax to denote the opposite 
> of what it normally means (that the rhs is being assigned). You 
> are better off I think just calling it like a function:
>
> s.castTo(i);
> s.castTo(str);
>
> Without knowing what castTo is supposed to do, if I saw 
> s.castTo = i, I would not expect at all that i is going to 
> change.
>
> -Steve

I consider alias this to be a mistake. There are simply too many 
bugs for it, as it does more than implicit conversion. The dlang 
would be better off if it were to implement opImplicitCast for 
lvalues while implicit constructors for rvalues. While putting 
alias this into maintenance mode, and discouraging future use of 
it.
We make it opt-in for functions to avoid the same mistake as c++ 
did.


More information about the Digitalmars-d mailing list