Casting by assigning to the right ...
Manfred Nowak
svv1999 at hotmail.com
Tue Apr 14 05:56:39 UTC 2020
... 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);
}
```
More information about the Digitalmars-d
mailing list