I have structs and classes that I'd like to be able to easily create from strings in a generic fashion, using the to!T(string)
method. However, I'm not sure how I could 'override' the method to get this kind of behavior. Going from my type to the string is easy (I would just define opCast(string)
), but is what I'm looking for even possible?
Don't define an opCast
for string
if you want your type to convert to string
. That's what toString
is for. writeln
and format
and the like use toString
, not casting or to
, and to
will use toString
, so it's definitely better to define toString
for converting to to string
. You define opCast
for converting to types other than string
. Then you can use that with casting or with to
.
Now, if you want to convert a string
to your user-defined type, then just define the appropriate constructor, and that will work with to
.
import std.conv;
struct S
{
int i;
this(string s)
{
i = to!int(s);
}
string toString()
{
return to!string(i);
}
}
void main()
{
auto s = to!S("42");
assert(s.i == 42);
auto t = to!string(s);
assert(t == "42");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With