9

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?

1 Answer 1

11

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");
}
1
  • Fantastic, didn't realize it was that simple! Commented Dec 20, 2011 at 0:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.