Object Cast

Kenji Hara k.hara.pg at gmail.com
Thu Jun 21 07:18:27 PDT 2012


On Thursday, 21 June 2012 at 10:33:41 UTC, Namespace wrote:
> To solve the problem of converting a Object to a specific 
> template class i wrote this little function.
> But the mixin disturbs me. How i can get the type (in this 
> example Vector2D) without to mix a mixin and T.stringof?
>
> [code]
> T object_cast(T : Object)(Object value) {
> 	T val = cast(T) value;
> 	
> 	if (val !is null) {
> 		return val;
> 	}
> 	
> 	// if cast fails it is a template class
> 	
> 	import std.typetuple;
> 	
> 	foreach (Type; TypeTuple!(byte, ubyte, short, ushort, int, 
> uint, long, ulong, float, double, real)) {
> 		mixin("
> 		if (auto vec = cast(" ~ T.stringof ~ "!(" ~ Type.stringof ~ 
> "))(value)) {
> 			return cast(T) vec;
> 		}");
> 	}
> 	
> 	return null;
> }
> [/code]

If you use 2.060head (git version), you can get template from the 
instantiated type.

class Vec(T) {}

void main()
{
     alias Vec!int IntVec;
     static if (is(IntVec _unused : V!T, alias V, T))
     {
         // V is class template Vec
         alias V!double DoubleVec;  // another type instantiation 
test
         static assert(is(DoubleVec == Vec!double));  // equal!
     }
     else
         static assert(0);
}



More information about the Digitalmars-d-learn mailing list