Skip to content

Instantly share code, notes, and snippets.

@jpf91 jpf91/gist:937492
Created Apr 22, 2011

Embed
What would you like to do?
Swig4D class cast proposal
/*
* 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
You can’t perform that action at this time.