Incrementing a variable in CTFE?

anonymous anonymous at example.com
Fri Nov 9 11:10:13 PST 2012


On Friday, 9 November 2012 at 17:54:54 UTC, Maxime Chevalier 
wrote:
> I'm using the mixin statement to generate function declarations 
> based on data structure descriptions (my attempt at declarative 
> programming).
>
> I'd like to be able to increment a variable each time I 
> evaluate my code generation function in the mixin statement. 
> This is so I can generate a unique id number for each data 
> structure. Is there any way to do this? Could I increment a 
> CTFE global somehow, or use something like C's static local 
> variables?

I don't see what exactly you're trying to achieve, but I had a 
similar problem regarding generating unique IDs at compile time.
I wanted different mixed-in values to have different types even 
if the template arguments were the same. A static counter would 
have worked for that, but no can do at compile time. The solution 
I came up with was to use types for IDs:

struct Quantity(Id) {int value;}
mixin template BasicUnit(string name) {
	struct Id {}
	mixin("enum " ~ name ~ " = Quantity!Id(1);");
}
struct Foo {mixin BasicUnit!"x";}
struct Bar {mixin BasicUnit!"x";}
static assert(!is(typeof(Foo.x) == typeof(Bar.x)));



More information about the Digitalmars-d-learn mailing list