www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Incrementing a variable in CTFE?

reply "Maxime Chevalier" <maximechevalierb gmail.com> writes:
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?
Nov 09 2012
next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
Maxime Chevalier:

 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?
CTFE allows you to use only locally pure code. So you can't modify globals or other static mutables. I have several times suggested to add to D something similar to the Gensym you see in CommonLisp. But maybe you are able to keep a local counter inside the function that calls the functions that generate the strings. Bye, bearophile
Nov 09 2012
prev sibling parent "anonymous" <anonymous example.com> writes:
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)));
Nov 09 2012