Casting by assigning to the right ...

Steven Schveighoffer schveiguy at gmail.com
Tue Apr 14 12:28:00 UTC 2020


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


More information about the Digitalmars-d mailing list