www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - mixin template and const property qualifier?

reply "aldanor" <i.s.smirnov gmail.com> writes:
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
Dec 15 2014
parent reply "anonymous" <anonymous example.com> writes:
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.
Dec 15 2014
parent "aldanor" <i.s.smirnov gmail.com> writes:
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!
Dec 16 2014