String mixin in templates

Andrej Mitrovic andrej.mitrovich at gmail.com
Tue Sep 18 09:14:22 PDT 2012


On 9/18/12, Andre <andre at s-e-a-p.de> wrote:
> snip

Templates introduce a new scope and in that scope 'var' doesn't exist,
what you want are template mixins (note: mixin expressions and
template mixins are different things):

mixin template test2(string str){
        void test2(){
                mixin("writeln(" ~ str ~ ");");
        }
}

void main() {
mixin test2!"var";
}

Note that you don't have to pass the variable by a string, you can use
an 'alias' and get rid of that mixin altogether:

mixin template test2(alias symb)
{
    void test2()
    {
        writeln(symb);
    }
}

void main()
{
    string var = "Hello World!";
    mixin test2!var;
}


More information about the Digitalmars-d-learn mailing list