www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - static if or version for CTFE

reply bmeck <bmeck stedwards.edu> writes:
I have a situation where I want to use a template if CTFE is possible and a
function if it can only be processed at runtime. is there a version or static
if which can check this?
Aug 27 2008
parent reply "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"bmeck" <bmeck stedwards.edu> wrote in message 
news:g956t5$18vg$1 digitalmars.com...
I have a situation where I want to use a template if CTFE is possible and a 
function if it can only be processed at runtime. is there a version or 
static if which can check this?

I think you may be able to do this in D2 with __traits(compiles). I can't test it, but you could try writing some code that would mixin a constant declaration with the expression you wish to evaluate. I.e. static if(__traits(compiles, mixin("enum x = yourExpression;"))) // it can be evaluated at compile time else // at runtime, or not at all if it's just an error In D1 I don't think there's any way.
Aug 27 2008
parent reply bmeck <bmeck stedwards.edu> writes:
Well im using D1 so if anyone knows of a way that would be lovely, the basics
are this:

template foo(char[] src)
{
    static if(src available at compile time for CTFE /*Ie is src const*/)
        blah;
    else
        blah;
}
Aug 27 2008
parent reply bmeck <bmeck stedwards.edu> writes:
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;
	}
}
Aug 27 2008
parent Max Samukha <samukha voliacable.com.removethis> writes:
On Thu, 28 Aug 2008 01:46:06 -0400, bmeck <bmeck 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")'
Aug 27 2008