Typed variadic template syntax?

Idan Arye GenericNPC at gmail.com
Thu Jan 30 18:32:46 PST 2014


On Thursday, 30 January 2014 at 23:06:36 UTC, deadalnix wrote:
> On Thursday, 30 January 2014 at 11:19:33 UTC, Idan Arye wrote:
>> Two problems:
>>
>> 1) You can't use `foreach` outside functions. That means that 
>> you write:
>>    struct Foo{
>>        foreach(i;TypeTuple!(1,2,3)){
>>            mixin("int num"~i.stringof~";");
>>        }
>>    }
>>
>
> mixin({ foreach(...) { ... } }())

Except it doesn't work inside classes and structs - it complains 
that "function literals cannot be class members". You have to 
define a named function and pollute the namespace.

>> 2) `foreach` creates it's own scope. This won't work:
>>    foreach(i; TypeTuple!(1,2,3)){
>>        mixin("int num"~i.stringof~";");
>>    }
>>    num1=1;
>>    num2=2;
>>    num3=3;
>>    writeln(num1,num2,num3);
>
> You got to mixin the whole stuff, not field by field, and you
> won't have any issue.

Yes, you can concatenate strings to create code. I've already 
answered to Ilya about that, so I'm going to copy-paste my answer:
"
Having complex strings mixing also means that if there is a
problem in that string, the compiler will point to the line where
the string is mixed in, not the one where the code that
introduces the error is concentrated to the string. Having a
static foreach will make the string mixins small and simple
enough for this to not be a problem.

Metaprogramming by building the code strings is not something
that should be encouraged(*cough* C macros *cough*), but it's
currently required sometimes for complex metaprogramming in D. If
we had static foreach we would still need string mixins, but at
least we will be mixing in many small simple strings instead of
one big complex string, and that means we could add to Phobos
some helper template mixins for sanitizing the arguments for
those mixins.
"


More information about the Digitalmars-d mailing list