Created
April 22, 2011 20:15
-
-
Save jpf91/937492 to your computer and use it in GitHub Desktop.
Swig4D class cast proposal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* C++ Class structure: | |
* | |
* Shape | |
* |- Circle | |
* |- Rectangle | |
* |-Square | |
* | |
*/ | |
extern(C) | |
{ | |
void* swig_cpp_cast_shape_circle(void*); | |
void* swig_cpp_cast_shape_rectangle(void*); | |
void* swig_cpp_cast_shape_square(void*); | |
void* swig_cpp_cast_rectangle_square(void*); | |
} | |
public class Shape | |
{ | |
T opCast(T) if (is(T : Shape) && __traits(compiles, T.castFrom(this))) | |
{ | |
return T.castFrom(this); | |
} | |
} | |
public class Circle | |
{ | |
static Circle castFrom(Shape shape) | |
{ | |
void* ptr = swig_cpp_cast_shape_circle(shape.getCPtr()); | |
if(ptr == null) | |
return null; | |
else | |
return new Circle(ptr); | |
} | |
T opCast(T) if (is(T : Circle) && __traits(compiles, T.castFrom(this))) | |
{ | |
return T.castFrom(this); | |
} | |
} | |
public class Rectangle | |
{ | |
static Rectangle castFrom(Shape shape) | |
{ | |
void* ptr = swig_cpp_cast_shape_rectangle(shape.getCPtr()); | |
if(ptr == null) | |
return null; | |
else | |
return new Rectangle(ptr); | |
} | |
T opCast(T) if (is(T : Rectangle) && __traits(compiles, T.castFrom(this))) | |
{ | |
return T.castFrom(this); | |
} | |
} | |
public class Square | |
{ | |
static Square castFrom(Shape shape) | |
{ | |
void* ptr = swig_cpp_cast_shape_square(shape.getCPtr()); | |
if(ptr == null) | |
return null; | |
else | |
return new Square(ptr); | |
} | |
static Square castFrom(Rectangle rect) | |
{ | |
void* ptr = swig_cpp_cast_rectangle_square(rect.getCPtr()); | |
if(ptr == null) | |
return null; | |
else | |
return new Square(ptr); | |
} | |
T opCast(T) if (is(T : Square) && __traits(compiles, T.castFrom(this))) | |
{ | |
return T.castFrom(this); | |
} | |
} | |
unittest | |
{ | |
void* ptr = someFunctionReturningAShapePtr(); | |
Shape shape = new Shape(ptr); | |
auto circle = cast(Circle)shape; | |
if(!Circle) | |
{ | |
auto rectangle = cast(Rectangle)shape; | |
if(rectangle) | |
auto square = cast(Square)rectangle; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment