Implicit conversion from string to custom type?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Feb 14 17:04:19 PST 2016


On 02/14/2016 03:43 PM, Tofu Ninja wrote:
> So I wrote a simple ref counted string type because using the built in
> strings without the GC is extremely painful. It there any way I can get
> strings to implicitly convert to my custom string type?

No, D does not support such implicit conversions.

> struct rstring {...}
> void fun(rstring s) {...}
> ...
> fun("hello world"); // Currently an error
>
> Would be super nice if it would just call the opAssign when trying to
> call fun but I suppose that has some non-obvious problems for why it
> does not work that way.

The only way is to be explicit. Three common options:

     fun(rstring("hello world"));
     fun("hello world".to!rstring);
     fun(cast(rstring)"hello world");

Relatedly, user defined types can provide implicit conversions through 
'alias this' but unfortunately, current implementation supports only one 
such operator.

Ali



More information about the Digitalmars-d-learn mailing list