Casting by assigning to the right ...
aliak
something at something.com
Tue Apr 14 13:03:19 UTC 2020
On Tuesday, 14 April 2020 at 05:56:39 UTC, Manfred Nowak wrote:
> ... is already builtin via properties.
>
> After declaring
> ```
> struct S{ int data;}
> S s;
> int i;
> ```
>
> one often would like to implicitly cast the value of the
> structure by typing
> ```
> i= s;
> ```
>
> According to the logged changes (
> https://digitalmars.com/d/2.0/changelog.html) a thought on this
> was published in 2008/03 for D2.012: `opImplicitCast', but not
> implemented since.
>
> Therefore one still has to introduce an `opCast' into `S' and
> then write
> ```
> i= cast( int) s;
> ```
>
> I do not like to always correctly examine the type of the
> variable I am assigning to ( `i' in this case) for using that
> type in the `cast()' and came up with the idea to no more
> assign to the left but to the right:
> ```
> s.castTo =i;
> ```
>
> Of course one has to define the property `castTo' within `S',
> but that has the signature
> `void castTo( ref int arg)'
> which is as simple as the signature of `opCast'. A runnable
> example follows. What do you think?
>
>
> ```
> struct S{
> string data;
> int opCast( T: int)(){
> import std.conv: to;
> return to!int( data);
> }
> void castTo( ref int arg){
> arg= cast( int) this;
> }
> }
> void main(){
> auto s= S( "42");
> int i;
> s.castTo =i;
> import std.stdio;
> writeln( i);
> }
> ```
Always a fan of generalizing patterns as long as they are
readable! So I would agree with Steven that
s.castTo = i
would be a bit confusing to review. And:
s.castTo(i);
would also be confusing in that it sounds like it's casting s to
i as in, turning s in to an i. But it's hard to know what that
can actually mean.
Also, you can make it a generic free function if you want. I.e.
turn this:
struct S {
void castTo( ref int arg){
arg= cast( int) this;
}
}
to:
void castTo(Source, Dest)(ref Source source, ref Dest dest) {
dest = cast(Dest)source;
}
And now you can have your i on the left hand side and maybe name
it something like castAssign and have code that reads like
i.castAssign(s); // cast and assign s
More information about the Digitalmars-d
mailing list