Associative Array & different template types

ag0aep6g anonymous at example.com
Wed Jul 3 19:07:10 UTC 2019


On 03.07.19 20:20, Robert M. Münch wrote:
> So, I need to carry around the object from which a delegate was created 
> from because it's not possible to query the delegate for the object 
> later somewhere else in the code.

It is possible to get the context object out of a delegate:

----
class C { void method() {} }
void main()
{
     auto c = new C;
     void delegate() dg = &c.method;
     assert(cast(C) dg.ptr is c); /* passes */
}
----

You just have to know (or carry around) the type so that you can cast 
correctly.

[...]
> myObject[string] myObjectArray;
> 
> auto mo1 = makeMyStruct!myClassA(mcA, &mcA.myClassFunc); // mo1 = myObject
> auto mo2 = makeMyStruct!myClassB(mcB, &mcA.myClassFunc); // mo2 = myObject
> 
> myObjectArray["1"] = mo1;
> myObjectArray["2"] = mo2;
> 
> assert(mcA == mo1._context)
> assert(mcA == myObjectArray["1"]._context)

class MyClassA { void myClassFunc() {} }
class MyClassB { void myClassFunc() {} }

void main()
{
     void delegate()[string] myDelegateArray;

     auto mcA = new MyClassA;
     auto mcB = new MyClassB;

     auto dg1 = &mcA.myClassFunc;
     auto dg2 = &mcB.myClassFunc;

     myDelegateArray["1"] = dg1;
     myDelegateArray["2"] = dg2;

     assert(mcA is cast(MyClassA) dg1.ptr); /* passes */
     assert(mcA is cast(MyClassA) myDelegateArray["1"].ptr); /* passes */

     /* When void* is good enough, you can use .ptr without a cast: */
     assert(dg2.ptr is myDelegateArray["2"].ptr); /* passes */
}


More information about the Digitalmars-d-learn mailing list