const member function

rumbu via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 20 23:31:18 PST 2015


On Saturday, 21 February 2015 at 07:01:12 UTC, Baz wrote:
> ---
> class S
> {
>     private SomeType cache;
>
>     public const(SomeType) SomeProp() @property
>     {
>        if (cache is null)
>          cache = SomeExpensiveOperation();
>        return cache;
>     }
> }
> ---
>
> the result of the getter will be read-only

My intention is not to have a read-only getter, I want to call 
SomeProp on a const object:

class S
{
     private int cache = -1;
     private int SomeExpensiveOp() { return 12345; }

     public @property const(int) SomeProp()
     {
         if (cache = -1)
             cache = SomeExpensiveOp();
         return cache;
     }
}

unittest
{
     const(S) s = new S();
     auto i = s.SomeProp;  //mutable method S.SomeProp is not 
callable using a const object
}


More information about the Digitalmars-d-learn mailing list