
Covariance and Contravariance in C++ Standard Library - ingve
http://cpptruths.blogspot.com/2015/11/covariance-and-contravariance-in-c.html
======
Sharlin
It is probably worth mentioning that the standard containers (and in general,
any mutable container) cannot be covariant in their element type without
compromising soundness. A vector<Circle•> should not have a push_back(Shape•)
member function inherited from vector<Shape•>. (However, a vector<Circle•>
could be safely _copied_ to a vector<Shape•> via an implicit conversion.) Java
arrays infamously covary, leading to dreaded ArrayStoreExceptions if misused.

(Edit: any way to write literal asterisks in HN?)

~~~
im2w1l
Java has a nice solution: An ArrayList<Ellipse> is an ArrayList<? extends
Shape>. But it is also an ArrayList<? super Circle>.

The former is "read-only" (can read elements which are all guaranteed to be
shapes). The latter is "write-only" (we can add circles to it, but not all
elements in it are guaranteed to be circles).

I use quotes because it is not strictly true, but any writes or reads will be
of the sort that they don't cause type problems. For instance you can call
clear() on a ArrayList<? extends Shape>

