Casting by assigning to the right ...
Mathias LANG
geod24 at gmail.com
Tue Apr 14 06:15:14 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;
> ```
There's two easy ways to accomplish this:
```
struct S
{
int data_;
version (OpAssign) ref S opAssign (int v) { this.data_ = v;
return this; }
version (AliasThis)
{
@property ref int data (int v) { this.data_ = v; return
this.data_; }
alias data this;
}
}
void main ()
{
S s;
int i;
s = i;
}
```
Which one you pick depends on your design. I would recommend the
`OpAssign` version by default.
More information about the Digitalmars-d
mailing list