Delegates and classes for custom code.

Simen Kjærås simen.kjaras at gmail.com
Tue Apr 17 11:29:40 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!

Depending on exactly what you want to do, this may be impossible, 
or bauss' code might fit the bill, or you could use anonymous 
classes:


class viewport_t
{
     int x,y,w,h;
}

class dialog_t
{
     int x,y;

     this( int x, int y)
     {
         this.x = x;
         this.y = y;
     }

     void draw_text(string text)
     {
     }

     abstract void on_draw(viewport_t);
}

void fn()
{
     viewport_t v;
     auto d = new class dialog_t {
         this() { super(15,15); }
         override void on_draw(viewport_t) {
             draw_text("hello world");
         }
     };
}

--
   Simen


More information about the Digitalmars-d-learn mailing list