mixin template question

Paul D Anderson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Apr 11 23:24:20 PDT 2015


On Sunday, 12 April 2015 at 04:04:43 UTC, lobo wrote:
> On Sunday, 12 April 2015 at 03:51:03 UTC, Paul D Anderson wrote:
>> I don't understand why the following code compiles and runs 
>> without an error:
>>
>> import std.stdio;
>>
>> mixin template ABC(){
>>  int abc() { return 3; }
>> }
>>
>> mixin ABC;
>>
>> int abc() { return 4; }
>>
>> void main()
>> {
>>  writefln("abc() = %s", abc());
>> }
>>
>> Doesn't the mixin ABC create a function with the same 
>> signature as the "actual function" abc()?
>>
>> It compiles with both included and writes "abc() = 4". If I 
>> comment out the actual function then it writes "abc() = 3". 
>> The actual function takes precedence, but why don't they 
>> conflict?
>>
>> Paul
>
> As the manual says (snippet below) the surrounding scope 
> overrides mixin
>
> http://dlang.org/template-mixin.html
>
> ---
> Mixin Scope
> The declarations in a mixin are ‘imported’ into the surrounding 
> scope. If the name of a declaration in a mixin is the same as a 
> declaration in the surrounding scope, the surrounding 
> declaration overrides the mixin one:
> int x = 3;
>
> mixin template Foo()
> {
>     int x = 5;
>     int y = 5;
> }
>
> mixin Foo;
> int y = 3;
>
> void test()
> {
>     writefln("x = %d", x);  // prints 3
>     writefln("y = %d", y);  // prints 3
> }
> ---
>
> bye,
> lobo

Thanks.



More information about the Digitalmars-d-learn mailing list