Implicit type conversion depending on assignment

user1234 user1234 at 12.de
Thu Mar 23 14:17:25 UTC 2023


On Thursday, 23 March 2023 at 14:05:07 UTC, Alexander Zhirov 
wrote:
> 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 an [example from the 
> documentation](https://dlang.org/spec/struct.html#alias-this), 
> but for "several" types, for example, with a cast check and a 
> return of the default value.

The best I can think of ATM

```
struct MyVal
{
     string value;
     auto opCast(T)()
     {
         import std.conv : to;
         return to!T(value);
     }
}

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

     int MyInt       = cast(int)a;
     float myFloat   = cast(float)b;
}
```

not exactly thing goal yet. The doc example you have put a link 
for is different, the struct with alias this a redefinition of 
the "alias this"'ed thing, that just cant work in what you ask in 
the first post.


More information about the Digitalmars-d-learn mailing list