February 14, 2016 Implicit conversion from string to custom type? | ||||
|---|---|---|---|---|
| ||||
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?
Some way to make this work...
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.
| ||||
February 14, 2016 Re: Implicit conversion from string to custom type? | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Tofu Ninja | 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 | |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply