Implicit type conversion depending on assignment

Jacob Shtokolov jacob.100205 at gmail.com
Fri Mar 24 09:39:00 UTC 2023


On Thursday, 23 March 2023 at 13:38:51 UTC, Alexander Zhirov 
wrote:
> Is it possible to convert such records inside the structure to 
> the assigned type?
>
> ```d
> struct MyVal
> {
>     string value;
>     // Here it would be possible to use an alias to this, but 
> it can only be used 1 time
> }
>
> auto a = MyVal("100");
> auto b = MyVal("11.2");
>
> int MyInt = a;        // Implicitly convert to target type
> float myFloat = b;    // Implicitly convert to target type
> ```

Here is another working variation of Ali's code, try it yourself:

```d
import std.stdio;
import std.conv;

struct MyVal
{
     string value;
     T opCast(T)() { return value.to!T; }
}

void main()
{
     auto a = MyVal("100");
     auto b = MyVal("11.2");

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

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

In general, all type casting and parsing stuff usually exist 
under `std.conv` in the standard library, so you can take 
advantage of it.


More information about the Digitalmars-d-learn mailing list