compile-time variables?
Pragma
ericanderton at yahoo.removeme.com
Wed May 23 05:15:00 PDT 2007
Fraser wrote:
> Thanks for the ideas! Unfortunately, it doesn't seem to be working (either way). Here's the complete code I tried:
>
> --------------------
> import tango.io.Stdout;
>
> char[] ctfe_itoa(uint value)
> {
> if (value < 10) return "0123456789"[value .. value+1];
> return ctfe_itoa(value / 10) ~ ctfe_itoa(value % 10);
> }
>
> uint Counter(){
> return 1;
> }
>
> uint Counter(in uint value){
> return value+1;
> }
>
> uint nextID()
> {
> const auto first = Counter();
> const auto second = Counter(first);
> const auto third = Counter(second);
> return third;
> }
>
> template Foo(char[] name)
> {
> const char[] text = "const char[] " ~ name ~ " = \"Name: " ~ name ~ ", ID: " ~ ctfe_itoa(nextID()) ~ "\n\";";
> }
>
> mixin(Foo!("a").text);
> mixin(Foo!("b").text);
> mixin(Foo!("c").text);
> mixin(Foo!("d").text);
> mixin(Foo!("e").text);
> mixin(Foo!("f").text);
>
> int main(char[][] args)
> {
> Stdout(a)(b)(c)(d)(e)(f);
> return 0;
> }
> --------------------
>
> The result was:
> Name: a, ID: 3
> Name: b, ID: 3
> Name: c, ID: 3
> Name: d, ID: 3
> Name: e, ID: 3
> Name: f, ID: 3
>
> A similar thing happened with the template example.
You need to prime your sequence with the zero counter value, and then keep passing a template instance around to
continue to count up:
template StartCounter(){
const uint next = 0;
}
template Foo(char[] name,alias counter)
{
const char[] text = "const char[] " ~ name ~ " = \"Name: " ~ name ~ ", ID: " ~ ctfe_itoa(counter.next) ~ "\n\";";
const uint next = counter.next + 1;
}
alias Foo!("a",StartCounter!()) foo_a;
alias Foo!("b",foo_a) foo_b;
alias Foo!("c",foo_b) foo_c;
alias Foo!("d",foo_c) foo_d; // <-- note how we feed the previous template back into the next template instance
alias Foo!("e",foo_d) foo_e;
mixin(foo_a.text);
mixin(foo_b.text);
mixin(foo_c.text);
mixin(foo_d.text);
mixin(foo_e.text);
--
- EricAnderton at yahoo
More information about the Digitalmars-d
mailing list