static if or version for CTFE

Max Samukha samukha at voliacable.com.removethis
Wed Aug 27 23:47:38 PDT 2008


On Thu, 28 Aug 2008 01:46:06 -0400, bmeck <bmeck at stedwards.edu> wrote:

>Sorry for double post but this works if a lil hackey and a dislikable branch occurs at runtime slowing it a bit...
>
>void main(char[][] args)
>{
>	Stdout(test("true")).newline;
>	Stdout(test(args[0])).newline;
>	
>}
>
>bool CTFE = true;
>static this()
>{
>	CTFE = false;
>}
>char[] test(char[] src)
>{
>	if(CTFE)
>	{
>		return src;
>	}
>	else
>	{
>		return src;
>	}
>}

No, both calls are executed at run time. Your test function does not
qualify for CTFE because it references mutable global state. To ensure
the function is executed at compile time put it in static context.

bool CTFE = true;
static this()
{
	CTFE = false;
}
char[] test(char[] src)
{
	if(CTFE)
	{
		return src;
	}
	else
	{
		return src;
	}
}

void main(char[][] args)
{
	pragma(msg, test("true"));
	writefln(test(args[0]));	
}

test.d(13): Error: variable CTFE is used before initialization
test.d(25): Error: cannot evaluate test("true") at compile time
test.d(25): Error: string expected for message, not 'test("true")'



More information about the Digitalmars-d mailing list