...ing logging 4.0

はてなブログに移行しました。D言語の話とかいろいろ。

Delegate covariance and contravariance

import std.stdio;

class A {}
class B : A {}

class X
{
	A foo() { return new A; }
}
class Y : X
{
	B foo() { return new B; }
}

class V
{
	void foo(B){}
}

void main()
{
	// Class Covariance (サポート済み)
	{
		X x = new X;
		Y y = new Y;
		A r = x.foo();
		A s = y.foo();
		B t = y.foo();
		writeln(r); // A
		writeln(s); // B
		writeln(t); // B
	}
	// Delegate Covariance
	{
		A delegate() f = delegate A() { return new A; }; // もちろんOK
		writeln(f()); // A
		
		//A delegate() g = delegate B() { return new B; }; // delegate covarianceのサポートが必要
		//writeln(g()); // Bになるべき
	}
	
	
	// Delegate Contravariance
	{
		V v = new V;
		void delegate(B) g = &v.foo; // もちろんOK
		//void delegate(A) f = &v.foo; // delegate contravarianceのサポートが必要
	}
}

適当にvotesしておくと幸せになれるかも(なれないかも).

2009年7月16日11時45分

Comment #1 From Steven Schveighoffer 2009-07-15 18:13:10 PDT -------

Your contravariance example is not valid, you cannot call foo(B) with an A.

It should be:

class V
{
void foo(A);
}


...

V v = new v;
void delegate(B) g = &v.foo; // contravariance

Also this is somewhat of a duplicate of bug 3075. Although you do bring up
covariance for delegates, which should be implemented at the same time as
contravariance.

Sadly, Walter has decided the prior bug is an invalid enhancement request, so
most likely nothing will come of this request either.

I think the only possible way this may be included is if someone implements it
and submits it as a patch to dmd.

あれー.僕のcontravarianceの解釈が間違ってるらしい.うーん.そうかあ.