Is there a standard way to define to for user-defined types?

Steven Schveighoffer schveiguy at yahoo.com
Mon Jun 20 05:52:38 PDT 2011


On Sun, 19 Jun 2011 23:22:23 -0400, Jonathan M Davis <jmdavisProg at gmx.com>  
wrote:

> For instance, if I want to make it legal to pass a  
> core.time.TickDuration to
> to!(core.time.Duration) instead of casting it (which is actually why  
> I've been
> think of this issue), what is the standard way to do that? Or isn't  
> there one?
> I'm not aware of one. And if there isn't one, how should we do it?
>
> I can think of 3 possible ways:
>
> 1. Overload to in the module with the type being converted from. So, for
> instance, core.time would have an overload for to which takes a  
> TickDuration
> and returns a Duration (either that or std.datetime if it didn't work to  
> have
> that in druntime for some reason). I'm not sure if that'll cause  
> problems with
> overload sets or not though.
>
> 2. Make it so that std.conv.to can do its thing based on opCast. If a  
> type
> overloads opCast, then std.conv.to can use that opCast to do the  
> conversion
> (but only if opCast is defined, not for just any cast which may or may  
> not be
> valid).
>
> 3. Make it so that user-defined types have a semi-standard member  
> function
> (e.g. to) which std.conv.to looks for and uses for conversions if it's  
> there.

I vote for 3.  However, it should not be called 'to', because you may want  
to call to!X(y) in a member function, which would resolve to your member  
to, not the global to.

-Steve


More information about the Digitalmars-d mailing list