alias this and immutable shenanigans

Stanislav Blinov blinov at loniir.ru
Fri Aug 13 04:22:18 PDT 2010


  13.08.2010 9:37, Yao G. wrote:
> Consider this code:
>
> ---
> module test;
>
> struct Foo
> {
>     this( int f ) {
>         _foo = f;
>     }
>
>     @property int baz() {
>         return _foo;
>     }
>
>     // alias _foo this;
>     // alias baz this;
>
>     immutable int _foo;
> }
>
> struct Bar
> {
>     this( int f ) {
>         _foo  = Foo(f);
>     }
>
>     private:
>     immutable Foo _foo;
> }
> ---
>
> If I uncomment the alias _foo this line, I get the following error 
> message:
>
> % Test.d(22): Error: can only initialize const member _foo inside 
> constructor
>
> WTF! I'm initializing it in a constructor! Is this a bug? Or by design 
> you cannot alias this to a immutable member of a struct. It seems that 
> there's a hidden temp created that wants to initialize the field. 
> Also, I wanted to alias the property Foo.baz, but it also caused the 
> following errors:
>
> % Test.d(22): Error: function test.Foo.baz () is not callable using 
> argument types (Foo) immutable
> % Test.d(22): Error: expected 0 arguments, not 1 for non-variadic 
> function type @property int()
>
> It seems that somehow the property is used as a "setter", not as a 
> "getter".
>
> So, my questions are:
> 1. Why is disallowed to alias this an immutable data inside a struct?
> 2. Why is disallowed to alias this a struct "getter" property?
>
>
If you rename Bar._foo to Bar._fooo, you'll see what it complains about 
(yep, about A._foo).

When you use 'alias x this', methods not defined for 'typeof(this)' will 
be searched in typeof(x). In this case, _foo = Foo( f ) is a constructor 
call, but...
If alias is present, _foo = Foo(f) translates to 
_foo._foo.opAssign(Foo(f)), or, when you alias to baz, to property 
assignment (and you indeed don't have a setter).

Thus being said, I'm not sure if it's a bug or not - seems like an 
ambiguity at least.

-- 
*
* 	

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20100813/bf4cc04b/attachment.html>


More information about the Digitalmars-d mailing list