http://d.puremagic.com/issues/show_bug.cgi?id=5719

           Summary: [patch] std.conv.to should support structs with custom
                    converters in addition to objects
           Product: D
           Version: D2
          Platform: Other
        OS/Version: Windows
            Status: NEW
          Keywords: patch
          Severity: normal
          Priority: P3
         Component: Phobos
        AssignedTo: nob...@puremagic.com
        ReportedBy: sandf...@jhu.edu


--- Comment #0 from Rob Jacques <sandf...@jhu.edu> 2011-03-07 21:50:57 PST ---
Currently std.conv.to allows classes to define custom conversion routines to
non-class types, but doesn't provide structs with the same functionality. This
functionality can be extended to structs by a minor change in one of the toImpl
template constraints from
is(S : Object) && !is(T : Object)
to 
((is(S : Object) && !is(T : Object)) || is(S == struct))

The particular toImpl is currently located at Line 687 in git (line 680 in DMD
2.051) and has been reproduced in full below with the patch, along with an
updated unit test. The patch passes the unit tests below and the unit tests in
my current fork of std.variant and std.json, but I haven't tested it against
the entire phobos test suite.

/**
Object-_to-non-object conversions look for a method "to" of the source
object.

Example:
----
class Date
{
    T to(T)() if(is(T == long))
    {
        return timestamp;
    }
    ...
}

unittest
{
    debug(conv) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, "
succeeded.");
    auto d = new Date;
    auto ts = to!long(d); // same as d.to!long()
}
----
 */
T toImpl(T, S)(S value) if ( ((is(S : Object) && !is(T : Object)) || is(S ==
struct)) && !isSomeString!T
        && is(typeof(S.init.to!(T)()) : T))
{
    return value.to!T();
}

unittest
{
    debug(conv) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, "
succeeded.");
    class B { T to(T)() { return 43; } }
    auto b = new B;
    assert(to!int(b) == 43);
    struct C { T to(T)() { return 43; } }
    C c;
    assert(to!int(c) == 43);
}

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------

Reply via email to