Cast Object - get null

Jakob Ovrum jakobovrum at gmail.com
Thu Apr 19 14:06:58 PDT 2012


On Wednesday, 18 April 2012 at 17:28:16 UTC, Jonathan M Davis 
wrote:
> Ideally, you'd also have a template constraint restricting the 
> cast to the
> types that you want to be able to cast to, but since you're 
> dealing with a
> templated type, that can be a bit tricky. One (somewhat ugly) 
> option would be
> to do something like
>
> U opCast(U) const
>  if(is(Unqual!U == Vector2D!byte) ||
>  is(Unqual!U == Vector2D!ubyte) ||
>  is(Unqual!U == Vector2D!short) ||
>  is(Unqual!U == Vector2D!ushort) ||
>  is(Unqual!U == Vector2D!int) ||
>  is(Unqual!U == Vector2D!uint) ||
>  is(Unqual!U == Vector2D!long) ||
>  is(Unqual!U == Vector2D!ulong) ||
>  is(Unqual!U == Vector2D!float) ||
>  is(Unqual!U == Vector2D!double) ||
>  is(Unqual!U == Vector2D!real))
> {
>  return new U(x, y);
> }
>
> Another would be to have an enum on the type indicating that 
> it's an
> instantiation of your Vector2D template (e.g. isVector2D).
>
> U opCast(U) const
>  if(__traits(compiles, U.isVector2D))
> {
>  return new U(x, y);
> }
>
> - Jonathan M Davis

T opCast(T : const(Vector2D!U), U)() const
{
     return new T(x, y);
}



More information about the Digitalmars-d-learn mailing list