Delegates and classes for custom code.

bauss jj_1337 at live.dk
Tue Apr 17 10:57:19 UTC 2018


On Tuesday, 17 April 2018 at 03:55:55 UTC, Chris Katko wrote:
> What I want:
>
> class viewport_t
>   {
>   int x,y,w,h;
>   }
>
> class dialog_t
>   {
>   int x,y;
>
>   this( int x, int y, delegate void (viewport_t) on_draw )
>     {
>     this.x = x;
>     this.y = y;
>     this.execute = execute;
>     }
>
>   void draw_text(string text)
>     {
>     }
>
>   delegate void (viewport_t) on_draw;
>   }
>
> void function()
>   {
>   viewport_t v;
>   dialog_t (15, 15,
>         delegate void (viewport_t)
>           {
>           draw_text("hello world"); //calls dialog_t function
>           }
>         )
>   }
>
> Is this possible? Pass to a class, the code to run. But the 
> code has to somehow know about the class methods.
>
> I don't think you can pass "dialog_t.this" as it's being 
> constructed!

First of all your code is not valid D code.

To construct a delegate you use the following syntax:

RETURN_TYPE delegate(PARAMS);

Ex. in your case:

void delegate(viewport_t);

Secondly, classes are reference types and thus you cannot 
construct just like:

viewport_t v;

It must be assigned using "new".

Ex.

auto v = new viewport_t;

The same goes for your dialog_t instance.

What you can do to avoid double allocation of dialog_t is to 
initially set it to void and thus you can point to the initial 
variable within your delegate that is constructed when dialog_t 
is actually constructed.

Ex.

     dialog_t d = void;
     d = new dialog_t (15, 15,
               delegate void (viewport_t)
               {
                   d.draw_text("hello world"); //calls dialog_t 
function
               }
     );

I could go into more details, but that would be completely 
unrelated to your issue at hand.


More information about the Digitalmars-d-learn mailing list