Templates convariance

michal.minich at gmail.com michal.minich at gmail.com
Tue Jun 20 09:57:31 PDT 2006


Now we have interfaces covariance working in D, but Templates covariance is not
implemented yet. Simply:

while you can write this:
Shape s = new Circle();

This fails to compile:
List!(Shape) sList = new List!(Circle)();

To show usefullness of this functionality, here is an example:

class Shape
{
void render()
{
printf ("Shape\n");
}
}

class Circle : Shape
{
void render()
{
printf ("Circle\n");
}
}


class List (T)
{
T item; // for simplicity, just one item possible in this list 
}

void renderShapes (List!(Shape) shapesList)
{
shapesList.item.render();
}

void main()
{
List!(Shape) shapesList = new List!(Shape) ();
shapesList.item = new Shape();

List!(Circle) circlesList = new List!(Circle) ();
circlesList.item = new Circle();

renderShapes ( shapesList ); // this works
//renderShapes ( circlesList ); // *1 - does not compile
renderShapes ( cast(List!(Shape))circlesList ); // *2 - access violation

}

// *1
//test.d(37): function test.renderShapes (List) does not match argument types
(List)
//test.d(37): cannot implicitly convert expression (circlesList) of type
test.List!(Circle).List to test.List!(Shape).List

// *2 application compiles, but when run, crashes with access violation


I think that implementation of this functionality can be very difficult, but
simply said, templates should be covariant if all its instantiation parameters
are covariant.





More information about the Digitalmars-d mailing list