www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Implicit conversion from string to custom type?

reply Tofu Ninja <emmons0 purdue.edu> writes:
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.
Feb 14 2016
parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
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
Feb 14 2016