std.conv.to

Steven Schveighoffer schveiguy at gmail.com
Mon Jun 20 13:32:24 UTC 2022


On 6/17/22 8:48 AM, harakim wrote:
> On Friday, 17 June 2022 at 12:31:45 UTC, harakim wrote:
>> I can generically convert a string to a type using to!type. I have a 
>> read function that does that. I have simplified the example below:
>>
>> ```d
>>     int readNumber()
>>     {
>>         return read!int(val => to!int(val), "number");
>>     }
>>
>>     string readTime()
>>     {
>>         return read!string(val => toTime(val), "time");
>>     }
>>
>>     private T read(T)(T function(string) transform, string typeName)
>>     {
>>         string input = readln();
>>             return transform(input);
>>     }
>> ```
>> However, I want to be able to convert my own custom types as well. How 
>> do I do that? Is there an operator overload I need to override for 
>> that? Do I have to static if on the template type and call the object?
> 
> I have no idea why I was stuck on this problem for so long. I can 
> specify anything I want in the transform and I even do in my own example 
> lol. I am still curious if there is a way to make your type work with 
> to!MyCustomType(source)

`to` uses natural hints that it can find via introspection. As others 
have pointed out, you can define a constructor in the target type to 
take the source type. To go the other way, you can define an `opCast` in 
the source type (if that's possible). If you want to convert to string 
(a specialized case), use a `toString` member function.

For class to class conversion, `to` will try a dynamic cast if none of 
the above is the case.

I believe there is no specific hook aside from these that allows you to 
define a conversion path.

-Steve


More information about the Digitalmars-d-learn mailing list