Thread overview
mixin template and const property qualifier?
Dec 15, 2014
aldanor
Dec 15, 2014
anonymous
Dec 16, 2014
aldanor
December 15, 2014
Could someone please explain why the following doesn't compile with "const" qualifier while it does work without it?

/* test.d */

module test;

mixin template Foo() {
    mixin("@property int bar() const { return foo; }");
}

int foo = 1;

mixin Foo;

unittest {
    assert(foo == bar);
}

> rdmd -main -unittest test.d
test.d-mixin-4(4): Error: function test.Foo!().bar without 'this' cannot be const
test.d(9): Error: mixin test.Foo!() error instantiating
December 15, 2014
On Monday, 15 December 2014 at 23:14:30 UTC, aldanor wrote:
> Could someone please explain why the following doesn't compile with "const" qualifier while it does work without it?
>
> /* test.d */
>
> module test;
>
> mixin template Foo() {
>     mixin("@property int bar() const { return foo; }");
> }
>
> int foo = 1;
>
> mixin Foo;
>
> unittest {
>     assert(foo == bar);
> }
>
>> rdmd -main -unittest test.d
> test.d-mixin-4(4): Error: function test.Foo!().bar without 'this' cannot be const
> test.d(9): Error: mixin test.Foo!() error instantiating

Has nothing to do with mixin. This produces the same error
message:

@property int bar() const { return foo; }
int foo = 1;
unittest {assert(foo == bar);}

The thing is, free functions cannot be const. In a const method,
what's const is `this`. A free function doesn't have `this`, so
it cannot be const.
December 16, 2014
On Monday, 15 December 2014 at 23:21:05 UTC, anonymous wrote:
> On Monday, 15 December 2014 at 23:14:30 UTC, aldanor wrote:
>> Could someone please explain why the following doesn't compile with "const" qualifier while it does work without it?
>>
>> /* test.d */
>>
>> module test;
>>
>> mixin template Foo() {
>>    mixin("@property int bar() const { return foo; }");
>> }
>>
>> int foo = 1;
>>
>> mixin Foo;
>>
>> unittest {
>>    assert(foo == bar);
>> }
>>
>>> rdmd -main -unittest test.d
>> test.d-mixin-4(4): Error: function test.Foo!().bar without 'this' cannot be const
>> test.d(9): Error: mixin test.Foo!() error instantiating
>
> Has nothing to do with mixin. This produces the same error
> message:
>
> @property int bar() const { return foo; }
> int foo = 1;
> unittest {assert(foo == bar);}
>
> The thing is, free functions cannot be const. In a const method,
> what's const is `this`. A free function doesn't have `this`, so
> it cannot be const.

Indeed... thanks!