Scope of Mixins

Ali Çehreli acehreli at yahoo.com
Thu Aug 26 17:39:16 UTC 2021


On 8/26/21 10:06 AM, Adam D Ruppe wrote:
> On Thursday, 26 August 2021 at 17:01:06 UTC, DLearner wrote:
>> The object was to take a variable, and do alternative things with it 
>> depending on (say) whether it was an 'int' or an 'int*'.
> 
> That's *very* easy to do with the alias. You can just check `typeof(v)` 
> in there.

String mixins are appealing because they can inject code like C macros 
do. It's not trivially possible to do the same with template mixins.

import std.traits : isPointer;
import std.stdio : writeln;

mixin template valueFrom(alias var)
if (isPointer!(typeof(var))) {
   writeln("Dereferencing a pointer");  // ERROR
   x = *var;
}

mixin template valueFrom(alias var)
if (!isPointer!(typeof(var))) {
   writeln("Using a scalar");           // ERROR
   x = var;
}

void main() {
   int x;
   int i = 42;
   mixin valueFrom!i;

   int * p = &i;
   mixin valueFrom!p;
}

Yes, there are tricks one can play or change the design but when it 
comes to "injecting code", template mixins are not as convenient as 
string mixins.

Ali


More information about the Digitalmars-d-learn mailing list