Search code examples
polymorphisminvokedinstance-methods

Non-polymorphically Invoke Instance Method in D?


How do you statically invoke a particular definition of an instance method from outside the class of the object, so as to inhibit polymorphism in that particular use? (In other words: I need the equivalent of Visual Basic.NET's MyClass, but from the outside.)


Solution

  • You can force the call by building a delegate and calling it. From memory:

    void delegate(int, float) dg;
    
    dg = &t.theFunction;  // gives the function for the dynamic type
    // OR
    dg.ptr = t;  // gives the object
    
    dg.funcptr = &typeof(t).theFunction; // gives the function for the static type 
    
    dg(1,3.1415);
    

    OTOH this is a hack in my book and for some types will be sure to cause problems.