Thread overview | |||||
---|---|---|---|---|---|
|
November 09, 2012 Incrementing a variable in CTFE? | ||||
---|---|---|---|---|
| ||||
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? |
November 09, 2012 Re: Incrementing a variable in CTFE? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Maxime Chevalier | 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
|
November 09, 2012 Re: Incrementing a variable in CTFE? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Maxime Chevalier | 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)));
|
Copyright © 1999-2021 by the D Language Foundation