CTFE determination?

Sergey Gromov snake.scaly at gmail.com
Fri Sep 12 15:09:31 PDT 2008


bmeck <bmeck at stedwards.edu> wrote:
> Well if it is available at CTFE I want to hash out as much as possible 
> calculations and store the result, if its not, dont mess with the data 
> and send it to a functions that does the same calculations and stores 
> the result at run time but in a different manner, namely allowing 
> pointers heap etc.

Got it.
This is the best I could come up with to the moment, but it works:

---
import std.stdio;

void main(string[] args)
{
	mixin CtfeIfPossible!( q{auto r1 =} , q{foo("test")} );
	mixin CtfeIfPossible!( q{auto r2 =} , q{foo(args[0])} );

	writeln(r1);
	writeln(r2);
}

string foo(string s)
{
	return s ~ "-modified";
}

template CompileTime(alias Expr)
{
	enum CompileTime = Expr;
}

template CtfeIfPossible(string Decl, string Expr)
{
	static if (__traits(compiles, CompileTime!(mixin(Expr))))
	{
		pragma(msg, "compile time ", Expr);
		mixin(Decl ~ "CompileTime!(" ~ Expr ~ ");");
	}
	else
	{
		pragma(msg, "runtime ", Expr);
		mixin(Decl ~ Expr ~ ";");
	}
}
---

It prints:

>dmd -run "test.d"
compile time foo("test")
runtime foo(args[0])
test-modified
C:\tmp\test.exe-modified



More information about the Digitalmars-d mailing list