Using template mixin, with or without mixin ?

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Apr 8 14:59:08 PDT 2017


On Saturday, 8 April 2017 at 09:47:07 UTC, biocyberman wrote:
> On Friday, 7 April 2017 at 23:53:12 UTC, Ali Çehreli wrote:
>>
>> The difference is that you can't use funcgen as a regular 
>> template:
>>
>>     funcgen!(void, void);
>>
>> Error: template instance funcgen!(void, void) mixin templates 
>> are not regular templates
>>
>> I think it's good practice to use 'mixin template' if it's 
>> intended to be so.
>>
>> Ali
>
> Thanks for a very concise answer.

In addition to Ali's answer, mixin templates do their symbol 
looking at the instantiation site, while regular templates do it 
at the declaration site. Example:

enum a = 0;

template test1()
{
	enum b1 = a; //Okay, a is in scope at the declaration site
	//enum c = d1; Error: undefined identifier d1
}

mixin template test2()
{
	enum b2 = a; //Okay, a is in scope at the declaration site
	enum c = d1; //Okay, d1 is in scope at the *instantiation* site
	//enum e = d2; Error: undefined identifier d2
}

void main()
{
	enum d1 = 0; //<--d1 is declared here
	mixin test1!();
	mixin test2!(); //<--so it is in scope here
	enum d2 = 0; //d2 was not declared before test2 was mixed in
                      //so it is not in scope for test2
}


More information about the Digitalmars-d-learn mailing list