Overloading opCast with multiple types

pragma ericanderton at yahoo.com
Mon Oct 2 18:47:04 PDT 2006


Stewart Gordon wrote:
> Reiner Pope wrote:
>> As we all know, opCast can only have one overload per class, because D 
>> doesn't support overloading by return type. That is a really silly 
>> limitation, in my opinion. Anyway, I have a solution here: give it a 
>> parameter, which is the type (we pass this parameter in the form of a 
>> template). Here's the magic:
>>
>> class Test
>> {
>>     int x;
>>     Foo myCast(TFoo : Foo)() { static assert(is(TFoo == Foo), "No cast 
>> of the required type exists"); return new Foo(x); }
> <snip>
> 
> Something to this effect has been proposed before.
> 
> However, the idea of having to put a static assert in each would make it 
> somewhat more cumbersome than it should be.  Moreover, a problem with 
> using templates is deciding how the vtbl would work.
> 
> There have been a number of proposals for ways to do multiple casts.
> 
> http://www.prowiki.org/wiki4d/wiki.cgi?FeatureRequestList
> 
> My proposal:
> 
> http://tinyurl.com/p2pn4
> 
> Stewart.
> 
> 

Well, while we're on the topic, I might as well mention this variant as 
well. :)

class Foobar{
   void* opCast(TypeInfo type){
     /* perform cast and return instance/value as needed
   }
}

Not only does this play fair with D's overload rules (no overload by 
return type) but it handles every possible case for casting, and IMO, is 
no more cumbersome than varargs are. For what it's worth, the runtime 
already does something similar when a dynamic cast is required.



More information about the Digitalmars-d mailing list