Coreect way to create delegate for struct method.

Alex sascha.orlov at gmail.com
Wed Aug 22 07:59:35 UTC 2018


On Wednesday, 22 August 2018 at 07:03:02 UTC, Andrey wrote:
> On Tuesday, 21 August 2018 at 22:52:31 UTC, Alex wrote:
>> Maybe, like this:
>
> Thank you but here you use heap to create ab object. I want 
> only on stack.
> I know that one can do this:
>> test_handler.ptr = null;
> and in place of call this:
>>handler.ptr = cast(void*)&this;
> but it is ugly...
>
> Hmm, any other ideas?

Ok... Another try:

´´´
import std.stdio;

struct Test
{
     void opAssign(Test)
     {
         "performing assignment".writeln;
         this.handler = &(this.one);
     }

     void one() const
     {
         writeln("In handler: Address = ", &this, "; Text = ", 
text);
     }

     void execute()
     {
         text = "Inited!";
         writeln("Before: Address = ", &this, "; Text = ", text);
         handler();
     }

     void delegate() handler = void;
     string text = "NoValue";
}

struct Qwerty
{
     void prepare()
     {
         _test = Test();
     }

     void execute()
     {
         _test.execute();
     }

private:
     Test _test  = void;
}

void main()
{
     Qwerty qwerty;
     qwerty.prepare();
     qwerty.execute();
}
´´´


More information about the Digitalmars-d-learn mailing list