Implicit type conversion depending on assignment

Jacob Shtokolov jacob.100205 at gmail.com
Fri Mar 24 11:27:56 UTC 2023


On Friday, 24 March 2023 at 09:59:47 UTC, Alexander Zhirov wrote:
> On Friday, 24 March 2023 at 09:46:26 UTC, Jacob Shtokolov wrote:
>> BTW, you can also `alias this` your struct value and then use 
>> `std.conv : to` for casting, if you don't need specific 
>> casting rules.
>
> I don't quite understand what you mean? Could you show me an 
> example?

I mean, it would be the same code except that you don't define 
any `opCast` or other operators for a struct, just alias the 
value to `this` and use `std.conv : to` directly as follows:

```d
struct MyVal
{
     string value;
     alias value this;
}

void main()
{
     import std.stdio;
     import std.conv;

     auto a = MyVal("100");
     auto b = MyVal("11.2");

     auto MyInt = a.to!int;
     auto myFloat = b.to!float;

     writeln(MyInt, ", ", myFloat);
}
```


More information about the Digitalmars-d-learn mailing list