Compile-time constness is waaay to strict!

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Sat Jul 25 02:43:42 PDT 2009


asd wrote:
> Jarrett Billingsley Wrote:
> 
>> Can you post more of your code?
> 
> I've reduced it to this:
> 
> 
> bool isEmptyString(string str) {		
> 	static if (str == "") return true;
> 	return false;
> }
> 
> void main()
> {
> 	static if (isEmptyString(""))
> 	{
> 		int x = 1;
> 	}
> }
> 
> 
> test.d(5): Error: expression str == "" is not constant or does not evaluate to a bool
> test.d(11): Error: cannot evaluate isEmptyString("") at compile time
> test.d(11): Error: expression isEmptyString("") is not constant or does not evaluate to a bool
> 
> DMD  v2.031 on OS X

This is definitely not a bug. You are mixing two different things here: 
templates and compile-time function evaluation (CTFE).

If you know you'll only need the isEmptyString functionality (or 
whatever it's representing) at compile time, you can write it as a 
template. str is then a template parameter which we can be sure is known 
at compile time, and we can use "static if" to check its value:

template isEmptyString(string str)
{
     static if (str == "")
         enum bool isEmptyString = true;
     else
         enum bool isEmptyString = false;
}


If isEmptyString is meant to be a function which can be executed at both 
compile and run time, you have to write it as an ordinary run-time 
function. You must then use an ordinary if, since it's impossible to 
know beforehand whether str is going to be set at run time or at compile 
time.

bool isEmptyString(string str)
{
     if (str == "") return true;
     return false;
}


Hope this helps,

-Lars



More information about the Digitalmars-d mailing list