Object Cast

Namespace rswhite4 at googlemail.com
Thu Jun 21 14:32:56 PDT 2012


Works in dmd  2.059 too.

[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]


More information about the Digitalmars-d-learn mailing list