Distinguishing between const and non-const variable in a template?

Tyler Knott tywebmail at mailcity.com
Thu Feb 22 16:45:26 PST 2007


renoX wrote:
> mario pernici a écrit :
>>
>> The else clause static if(is(typeof(s))) is to make
>> sure that s exists.
> 
> Mmm; how could s doesn't exist?
> D is supposed to be a statically typed language..
> 
> renoX

D is statically typed, but that has nothing to do with why the second test is needed.  Here's a quote from the language 
spec on the typeof(Expression) construct (http://www.digitalmars.com/d/declaration.html):

 > Expression is not evaluated, just the type of it is generated:
 > void func()
 > {   int i = 1;
 >     typeof(++i) j;	// j is declared to be an int, i is not incremented
 >     printf("%d\n", i);	// prints 1
 > }

And then if you look at the documentation for IsExpression, you'll see that invalid types used in the context of an 
IsExpression won't error, but instead cause the IsExpression to return 0 (false).  When you combine these two 
properties, it is legal and valid for D code to take the type of an undeclared variable (resulting in an invalid type) 
inside an IsExpression; e.g.:

void main()
{
     int foo;

     static assert(is(typeof(foo)), "foo is a valid variable."); //Valid, doesn't trip
     static assert(is(typeof(undeclaredVariable)), "undeclaredVariable is invalid."); //Valid, trips
     typeof(foo) bar; //Valid, bar is an int
     typeof(undeclaredVariable) bar; //"Error: undefined identifier undeclaredVariable"
}

This is why two tests are required for Mario Pernici's const dectector.  The first test determines if you can take the 
address of the variable, which fails for both const and invalid variables.  Then, it needs to make sure the variable 
actually exists by taking its type (invalid variables will fail here, but everything else will pass).


More information about the Digitalmars-d-learn mailing list