String Mixins & Compile Time Evaluation

Travis Boucher boucher.travis at gmail.com
Mon Nov 16 17:54:49 PST 2009


I've been playing with string mixins, and they are very powerful.

One thing I can't figure out is what exactly can and cannot be evaluated 
at compile time.

For example:

----
char[] myFunc1() {
     return "int a = 1;";
}

char[] myFunc2() {
     char[] myFunc3() {
         return "int b = 2;";
     }
     return myFunc3();
}

void main() {
     mixin(myFunc1());
     mixin(myFunc2());
}
----

myFunc1() can be used as a string mixin.
myFunc2() can't be.

Another (slightly more complex) example is using an ExpressionTuple.

----
template DataGenerator(T, M...) {
	char[] data() {
		char[] rv;
		foreach (m; M) rv ~= T.stringof ~ " " ~ m ~ ";";
		return rv;
	}
}

alias DataGenerator!(int, "r", "g", "b") ColorRGBgen;

writefln(ColorRGBgen.data()); // int R; int G; int B;

struct Color {
	mixin(ColorRGBgen.data()); // Can't evaluate at compile time
}
----


I'm sure there are other things that I'll run into, but I figure there 
is some simple set of rules of what can and can't be used as a string 
mixin and other compile time evaluations.


More information about the Digitalmars-d-learn mailing list