__traits(compiles, ...) returns true for syntactic garbage and for semantically incorrect code

Pavel proger79 at gmail.com
Mon Dec 17 06:15:41 PST 2012


On Monday, 17 December 2012 at 12:20:23 UTC, Pavel wrote:

> Oops, bad idea - it will work only for self-contained code but 
> will not work when code references some variables from current 
> scope.

Template mixin helps to solve the issue, so the utility template 
can be:

mixin template Compiles(string code)
{
    enum bool Result = __traits(compiles, mixin("{" ~ code ~ "}"));
}

with usage:

   enum string code1 = "int i = q{};";
   int j = 0;
   enum string code2 = "j++;";
   enum string code3 = "void foo(){}";
			
   mixin Compiles!code1 compilesCode1;
   mixin Compiles!code2 compilesCode2;
   mixin Compiles!code3 compilesCode3;
	
   writeln("Compiles `" ~ code1 ~ "`: " ~ 
to!string(compilesCode1.Result) );
   writeln("Compiles `" ~ code2 ~ "`: " ~ 
to!string(compilesCode2.Result) );
   writeln("Compiles `" ~ code3 ~ "`: " ~ 
to!string(compilesCode3.Result) );

It seems to me handier to use it from templates manipulating code 
as strings than usage of __traits(compiles,...) directly.

Pavel


More information about the Digitalmars-d mailing list