Fully transitive const is not necessary

Steven Schveighoffer schveiguy at yahoo.com
Wed Apr 2 14:01:12 PDT 2008


"Bill Baxter" wrote
> Janice Caron wrote:
>
>>
>>>  - a pure method cannot access the mutable portion of a logically 
>>> invariant
>>>  data value.
>>
>> Well, the easy way to do that is to redesign the class into two
>> classes, one const and the other not. That way, you get the exact same
>> benefit, but in addition, you end up saying what you mean, instead of
>> writing obfuscated code.
>
> I don't understand how to do what you're saying.  Here's the version using 
> mutable:
>
> class Calc
> {
>    private mutable int result_cache;
>    int calc_result(int) { .../*uses result_cache to save results*/ }
>    ...
> }
> auto x = new Calc;
> int y = x.calc_result(32);
>
> So how do you separate that into two classes?  How do I create an instance 
> of that two-class thing?  Via a third class?  How can Calc access its 
> cache?  The user has to pass in the cache to every call to calc_result? 
> The goal is for the caching to be an implementation detail that users need 
> not worry about.  The above seems about as straightforward as it gets. 
> Any else is probably going to have to come out *more* obfuscated.

I don't think you can even wrap the class, because what about this:

class CachedCalc
{
   Calc c;
   int result_cache;
}

class ConstCalc
{
   const(Calc) c;
   int result_cache;
}

This should work, but because ConstCalc and CachedCalc are not derived 
classes it doesn't:

ConstCalc cc = new CachedCalc();

So the only way to do it is to carry around both calc and the cache, and 
pass the cache in to every call that needs it.  I agree this is useless.

On top of that, you can't create a constructor that uses a CachedCalc, 
because you can't re-assign c, thanks to no tail-const class references...

-Steve 





More information about the Digitalmars-d mailing list