Code block as template argument

Ali Çehreli acehreli at yahoo.com
Tue Feb 11 11:34:49 UTC 2020


On 2/11/20 3:14 AM, Виталий Фадеев wrote:> On Tuesday, 11 February 2020 
at 11:10:44 UTC, Виталий Фадеев wrote:

 > Analog C-code with macros:
 >      #define TPL(M,D,CODE) if ( state & M && diraction = D ) CODE;
 > example code
 >      TPL( OPEN, OUT,
 >        {
 >          delete AppsWindow
 >          state &= !OPEN
 >        }
 >      )
 >
 > It possible in D ?

As a friendly reminder, the Learn newsgroup (or its Forum interface at 
https://forum.dlang.org/group/learn) is more appropriate for such questions.

Two options come to mind:

uint state;
enum uint OPEN = 0x2;
enum Direction { D, OUT }
Direction direction;

// Option 1: Equivalent of a C macro
void executeMaybe(Func)(uint M, Direction D, Func func) {
   if ((state & M) && (direction == D)) {
     func();
   }
}

// Option 2: Equivalent of a C struct
struct MaybeExecutor {
   uint M;
   Direction D;

   this (uint M, Direction D) {
     this.M = M;
     this.D = D;
   }

   auto opCall(Func)(Func func) {
     if ((state & M) && (direction == D)) {
       func();
     }
   }
}

void main() {
   int* AppsWindow;

   executeMaybe(OPEN, Direction.OUT, {
       destroy(*AppsWindow);
       state &= !OPEN;
     });

   auto ex = MaybeExecutor(OPEN, Direction.OUT);
   ex({
       destroy(*AppsWindow);
       state &= !OPEN;
     });
}

Ali




More information about the Digitalmars-d mailing list