do D support something like C# 4.0 co/contra-variance?
Michal Minich
michal.minich at gmail.com
Thu Sep 2 05:50:10 PDT 2010
On Thu, 02 Sep 2010 07:38:24 -0400, bearophile wrote:
> dennis:
>> http://blog.t-l-k.com/dot-net/2009/c-sharp-4-covariance-and-
contravariance
>
> I think D2 doesn't support those things yes. But they are useful and may
> be added to D3.
>
> Bye,
> bearophile
I did not explored this area much, but it seems thanks to duck typed D
templates, in some cases template covariance and contravariance is
achievable implicitly (see the code example).
It is also worth noting that C# does not support more simple OO feature -
covariant return types [1], which I really miss when programming in C#.
The variance of D templates may be quite hard to specify and implement,
given the genericity and complexity of templates. But I'm sure at least
some effects are implementable right now - like safe contra/variant cast;
and it should be also possible to add variable to types as variance
annotations, which are checkable at ct...I might look closer at this some
time..
[1] http://www.digitalmars.com/d/2.0/function.html
import std.stdio;
class Rect {
void draw () { writeln ("Rect"); } }
class RoundedRect : Rect {
override void draw () { writeln ("RoundedRect"); } }
class UltraRect : RoundedRect {
override void draw () { writeln ("UltraRect"); } }
class List (T) {
private T[] items;
void add (T item) { items ~= item; }
T[] getAll () { return items.dup; }
}
void fill (T) (List!(T) list) {
// list.add (new Rect); // errors here:
// function List!(RoundedRect).List.add (RoundedRect item)
is not callable using argument types (Rect)
// cannot implicitly convert expression (new Rect) of type
Rect to RoundedRect
list.add (new RoundedRect);
list.add (new UltraRect);
}
void drawAll (T) (List!(T) items) {
foreach (item; items.getAll())
item.draw();
}
void main () {
auto l = new List!(RoundedRect);
fill (l);
drawAll (l);
}
More information about the Digitalmars-d
mailing list