Coreect way to create delegate for struct method.

Andrey saasecondbox at yandex.ru
Tue Aug 21 21:29:38 UTC 2018


Hello,
This is a code:
>import std.stdio;
>
>struct Test
>{
>    static Test opCall()
>    {
>        Test test;
>        test.handler = &test.one;
> 
>        return test;
>    }
> 
>    void one() const { writeln("In handler: Address = ", &this, 
> "; Text = ", text); }
> 
>    void execute()
>    {
>        text = "Inited!";
>        writeln("Before: Address = ", &this, "; Text = ", text);
>        handler();
>    }
> 
>    void delegate() const 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();
>}

Here I try to make a delegate for struct "Test" and method 
"one()".
When I launch it then I get this output:
>Before: Address = 7FFC096A2C20; Text = Inited!
>In handler: Address = 7FFC096A2BE8; Text = NoValue

It means that my delegate captures one object of Test, but in 
place of call uses another...
I want just to save my method into variable and after that use it 
on some arbitrary object of type "Test". How to do it in D?

In C++ it is very easy:
> test.handler = &Test::one;
and call:
> (this->*handler)();
or
> (someTestObjPtr->*handler)();
I know axactly that in the first variant a context will be 
"this", and in the second - "someTestObjPtr".


More information about the Digitalmars-d-learn mailing list