Overloading opCast with multiple types

Reiner Pope reiner.pope at REMOVE.THIS.gmail.com
Sat Sep 30 15:25:15 PDT 2006


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); }
	Bar myCast(TBar : Bar)() { static assert(is(TBar == Bar),  "No cast of 
the required type exists"); return new Bar(x); }
	FooExtender2 myCast(T : FooExtender2)() { static assert(is(T == 
FooExtender2), "No cast of the required type exists"); return new 
FooExtender2(x); }
	this(int _x) {x = _x;}
}

and it is called like this:

	Test a = new Test(5);
	Foo f = a.myCast!(Foo); // Property syntax means the second () is 
unnecessary, so it looks almost like cast(Foo)a;
	Bar b = a.myCast!(Bar);
//	Useless u = a.myCast!(Useless); // Fails -- no template 
specialization exists
//	FooExtender t = a.myCast!(FooExtender); // Fails the static assert 
(TFoo == Foo)

This code works right now. The static asserts are necessary because 
template specialization doesn't have the expressiveness of is 
expressions. I want the ability to say, "use this specialization for 
this type only, and don't use it for the subtypes."

If this were supported under opCast, I would say that it should work by 
using templates as I have above, and adding a specialization type, so 
that templates could look like this: myCast(TFoo == Foo)() { return new 
Foo(x); }. (The '==' syntax is the noteworthy bit)

Let me know what you think,

Reiner



More information about the Digitalmars-d mailing list