Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override to!T() for used-defined T in D?

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?

like image 447
Mark LeMoine Avatar asked Dec 02 '11 02:12

Mark LeMoine


1 Answers

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");
}
like image 68
Jonathan M Davis Avatar answered Jan 01 '23 19:01

Jonathan M Davis