Object Cast

Kenji Hara k.hara.pg at gmail.com
Thu Jun 21 19:21:05 PDT 2012


On Thursday, 21 June 2012 at 21:32:57 UTC, Namespace wrote:
> Works in dmd  2.059 too.

Oh, good.

> [code]
> T template_cast(T : Object, U : Object)(U value) {
> 	// try to convert
> 	T val = cast(T) value;
> 	
> 	// if convert was successful, return
> 	if (val !is null) {
> 		return val;
> 	}
> 	
> 	// if cast fails it is a template class
>     static if (is(T ClassType : V!W, alias V, W)) {
>         // V is the template class
> 		import std.typetuple;
> 		
> 		// find out which one is "value"'s original type
> 		foreach (Type; TypeTuple!(byte, ubyte, short, ushort, int, 
> uint, long, ulong, float, double, real)) {
> 			// if found: cast
> 			writeln(Type.stringof);
> 			if (auto vec = cast(V!Type) value) {
> 				return cast(Unqual!T) vec;
> 			}
> 		}
> 		
> 		return null;
>     } else {
> 		return null;
> 	}
> }
> [/code]
>
> Example:
> [code]
> class Rect(T) {
> 	T opCast(T : inout(Rect!U), U)() inout {
> 		return new T();
> 	}
> 	
> 	override string toString() const {
> 		return "Rect!(" ~ T.stringof ~ ")";
> 	}
> }
>
> void foo(Object o) {
> 	write("O ist: ");
> 	writeln(o);
> 	
> 	write("self cast: ");
> 	writeln(cast(Rect!int) o);
> 	
> 	write("template cast: ");
> 	Rect!int ri = template_cast!(Rect!int)(o);
> 	
> 	write("Result: ");
> 	writeln(ri);
> }
>
> Rect!(float) rf = new Rect!(float)();
>
> foo(rf);
> [/code]

Seems to me that you achieved the your first purpose. Do you need 
more help?

Kenji Hara


More information about the Digitalmars-d-learn mailing list