What the heck is wrong with CTFE's?

John Colvin john.loughran.colvin at gmail.com
Mon Jul 8 05:41:21 PDT 2013


On Monday, 8 July 2013 at 11:56:40 UTC, JS wrote:
>
> The following code inserts properties for each type,
>
> auto name = "Value"~((i == 0) ? "" : to!string(i++));
>
> always as the i == 0 evaluate to true.
>
>
> My question is, why the heck is it so hard to use basic 
> programming structs inside CTFE's? I know that CTFE's have to 
> work at run time also, so there is a limitation, but:
>
> 1. obviously ints work because the code below works with i as a 
> counter but we can't do a simple compare on it... this seems 
> like a bug.
>
> 2. foreach can be used but a simple for loop can't... makes no 
> sense.
>
> I know what the average response is going to be but hopefully 
> someone will surprise me with some useful.
>
>
>
> mixin template PropertyBuilder(T...)
> {
> 	template _(TT...)
> 	{
> 		static string eval()
> 		{
> 			string s;
> 			pragma(msg, TT);
> 			int i = 0;
> 			foreach(t; TT)
> 			{
> 				auto name = "Value"~((i > 0) ? "" : to!string(i++));
> 				s = "@property "~t.stringof~" "~name~"();\n";
> 				s ~="@property "~t.stringof~" "~name~"("~t.stringof~" 
> value);\n";
> 			}
> 			return s;
> 		}
> 		enum _ = eval();
> 		pragma(msg, _);
> 	}
>
> 	mixin("mixin(_!T);");
> 	
> }
>
> interface a(MT...)
> {
> 	mixin PropertyBuilder!MT;
> }

after weeding out the bugs and unusual things, plus letting 
foreach manage i:

mixin template PropertyBuilder(T...)
{
	template _(TT...)
	{
		static string eval()
		{
			string s;
			foreach(i, t; TT)
			{
				auto name = "Value"~((i > 0) ? to!string(i) : "");
				s ~= "@property "~t.stringof~" "~name~"();\n";
				s ~="@property void "~name~"("~t.stringof~" value);\n";
				
			}
			return s;
		}
		enum _ = eval();
	}

	mixin("mixin(_!T);");
}

which works fine.

The i++ in to!string not having any effect is rather surprising, 
I agree.


More information about the Digitalmars-d mailing list