small template and mixin frustration...

WhatMeWorry via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 6 12:42:40 PDT 2015


// First attempt

string myDebug(string someSymbol)
{

     string doubleQuotes = "\" = \", ";
     string s = "writeln(__traits(identifier, " ~  someSymbol ~ 
")," ~
                 doubleQuotes ~ someSymbol ~ ");" ;
     return s;
}


// 2nd attempt - more generic - compile time errors at point of 
call.

string myDebug2(T)(T someSymbol)
{
     string doubleQuotes = "\" = \", ";
     string s = "writeln(__traits(identifier, " ~  
to!string(someSymbol)
                 ~ ")," ~ doubleQuotes ~ to!string(someSymbol) ~ 
");" ;
     return s;
}

// I thought just straight text replacement like here, but this 
fails at
// compile in the code block itself (this is not a function, 
right?)

template myDebug3(alias someSymbol)
{
     string doubleQuotes = "\" = \", ";
     writeln(__traits(identifier, " ~  someSymbol ~ ")," ~  
doubleQuotes ~ someSymbol ~ ");" ;
}



Trying to create the following statement programatically:

writeln(__traits(identifier, someSymbol), " = ", someSymbol);


GLfloat[6] staticVerts = [0.0, 1.0,-1.0, -1.0, 1.0, -1.0];
int i = 7;

mixin (myDebug("staticVerts"));  // This one works with output 
following
mixin (myDebug("i"));            // This one works with output 
following

staticVerts = [0, 1, -1, -1, 1, -1]
i = 7

So I thought it would be cool to get rid of the requirement for 
the arguments to be strings. That would make it simpler and also 
I could verify the arguments themselves.

What amazed me about D, was that I thought a typo like mixin 
(myDebug("taticVert")) would result in a run-time error.
but the compiler actually catches it!

However, with that said, I've spent so many hours beating my head 
against the wall that it has now become a matter of pride.  So,

mixin (myDebug2(staticVerts));   // Fails with the following...
mixin (myDebug2(i));             // Fails with the following...

MeGlWindow.d(72): Error: variable staticVerts cannot be read at 
compile time
MeGlWindow.d(72):        called from here: myDebug2(staticVerts)
MeGlWindow.d(72): Error: argument to mixin must be a string, not 
(myDebug2(staticVerts)) of type string
MeGlWindow.d(73): Error: variable i cannot be read at compile time
MeGlWindow.d(73):        called from here: myDebug2(i)
MeGlWindow.d(73): Error: argument to mixin must be a string, not 
(myDebug2(i)) of type string

Is what I'm trying to do possible?  Any suggestions or tips?  
Thanks.



More information about the Digitalmars-d-learn mailing list