www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Delegate Covariance?


http://msdn.microsoft.com/en-us/library/ms173174%28VS.80%29.aspx



class Mammals {}
class Dogs : Mammals {}

class Program {
    public delegate Mammals HandlerMethod();
    public static Mammals FirstHandler() { return null; }
    public static Dogs SecondHandler() { return null; }

    static void Main() {
        HandlerMethod handler1 = FirstHandler;
        HandlerMethod handler2 = SecondHandler;
    }
}


That works:
http://ideone.com/JoUF4rFk


So I have tried to translate it to D (using an 'HandlerMethod' alias and a
function pointer 'handler'):


class Mammals {}
class Dogs : Mammals {}
alias Mammals function() HandlerMethod;
Mammals function() handler;
Mammals FirstHandler() { return null; }
Dogs SecondHandler() { return null; }
void main() {
    HandlerMethod handler1 = &FirstHandler;
    HandlerMethod handler2 = &SecondHandler; // Err
    handler = &SecondHandler; // err
}


But that D2 code doesn't compile, it gives two errors. Can you help me
understand a little this situation for the D compiler? Can the D compiler
change the way it works here?

Thank you and bye,
bearophile
Mar 20 2010