"Semi-const" methods?
Mafi
mafi at example.org
Mon Mar 14 03:51:09 PDT 2011
Am 13.03.2011 23:27, schrieb Magnus Lie Hetland:
> I have a data structure that's generally static (const, or even
> immutable), but it has some utility storage, which caches certain
> results during use. This caching etc. doesn't really affect the
> semantics of the main object, and are reset between operations, so I
> think it still would be useful to declare (and statically check) that
> certain methods don't modify any of the *rest* of the structure (i.e.,
> the "main parts").
>
> I *could* declare the methods const, and pass in a second object (a
> non-const parameter) for the caching etc. Or I cast the relevant parts
> to const (assigning them to local variables) early on in the relevant
> methods (dropping the const modifier on the method itself -- sort of a
> bummer).
>
> Any other ideas on how to handle this sort of "mostly const" or "const
> where it counts" stuff? Perhaps my design intentions here are off to
> begin with?-)
>
I found away which doesn't use casts or bugs.
Just use delegates/closures.
class C {
int i;
int delegate(int) getCache;
this(int fi) {
this.i = fi;
int lastX, lastR;
this.getCache = (int x) {
if(x == lastX) return lastR;
lastX = x;
lastR = x * i;
return lastR;
};
}
const multiply(int x) {
return getCache(x);
}
}
More information about the Digitalmars-d-learn
mailing list