...ing logging 4.0

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

デリゲートと関数ポインタで共変の戻り値(covariance)

import std.stdio;

class Base  {}
class Derived : Base {}

void main()
{
    // Covariance
    {
        Base delegate() f = delegate Derived() { return new Derived; };
        writefln("delegate convariance is <%s>", f().toString() == "a.Derived" ? "OK" : "NG");
    }{
        static Derived fp() { return new Derived; }
        Base function() f = &fp;
        writefln("function pointer covariance is <%s>", f().toString() == "a.Derived" ? "OK" : "NG");
    }
    
    // Contravariance
    {
        auto c = new class { void foo(Base){} };
        
        // GOOD
        void delegate(Base) f = &c.foo;
        f(new Base);
        f(new Derived);
        
        // BAD
        //void delegate(Derived) g = &c.foo;
        //g(new Derived);
    }
}
delegate convariance is <OK>
function pointer covariance is <OK>


反変の方はまだダメみたい.

a.d(33): Error: cannot implicitly convert expression (&c.foo) of type void delegate(Base) to void delegate(Derived)