Purity, @safety, etc., in generic code
deadalnix
deadalnix at gmail.com
Fri Feb 22 22:07:51 PST 2013
On Friday, 22 February 2013 at 20:32:59 UTC, Jonathan M Davis
wrote:
> On Friday, February 22, 2013 14:31:55 Steven Schveighoffer
> wrote:
>> It is probably rare to have both a const and non-const
>> overload, that is
>> true, but it is not up to D to decide what design is best. We
>> should take
>> the most flexible approach, and allow designers to come up
>> with whatever
>> ideas they like. I don't think there is any significant extra
>> work
>> required to support const method overloads in the compiler, in
>> fact it
>> would be a more significant change to make that an exception.
>
> A prime example of where overloading on const can be useful is
> caching. You
> can write a function which caches its result for efficiency
> purposes, but the
> const version can't cache, whereas the non-const one can. So,
> you can do
> something like
>
> auto calculate()
> {
> if(_dirty)
> _cache = _doCalculation();
> return _cache;
> }
>
> auto calculate() const
> {
> if(_dirty)
> return _doCalculation();
> return _cache;
> }
>
> If you couldn't overload on const, then that wouldn't be
> possible. You'd be
> forced either to forgoe const and make it cache or to make it
> const and forgoe
> the caching.
>
Nothing prevent you from putting the cache outside the object.
More information about the Digitalmars-d
mailing list