Bug 3189 – `std.conv.to` : check for a custom `to` method in classes/structs

Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2009-07-18T10:04:00Z
Last change time
2015-06-09T05:13:44Z
Assigned to
andrei
Creator
julien

Comments

Comment #0 by julien — 2009-07-18T10:04:57Z
Hello, it would be nice if `std.conv.to` on class or struct could check if this class or struct implements its own `to` method. Something as : module Date; class Date { T to(T)() if(is(T == long)) { return timestamp; } } module std.conv; T to(T, S)(S s) if (is(S : Object) { static if(is(typeof(s.to!(T)()))) return s.to!(T)(); return /* whatever */; } module test; void main() { assert(to!(long)(new Date) == 123124142324); }
Comment #1 by andrei — 2009-08-28T08:28:09Z
Ok. I implemented this: /** 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 { auto d = new Date; auto ts = to!long(d); // same as d.to!long() } ---- */ T to(T, S)(S value) if (is(S : Object) && !is(T : Object) && !isSomeString!T && is(typeof(S.init.to!(T)()) : T)) { return value.to!T(); }