I'm writing an AA implementation, and ran into this problem with the way const behaves in D. Basically, I have an auxiliary function that searches the internal hash table for a given key, and returns the slot containing the matching entry, if found.
The problem is, how to write this function so that it can be called from *both* a const public method and a non-const public method? Since the method itself doesn't actually modify anything, it *should* in theory be possible to mark it as const: const Slot *findSlot(Key key) { ... } However, because the const applies to 'this', the compiler insists that referencing anything via 'this', including reading a pointer to a slot, must also be const, so it refuses to let the return type be Slot*; it has to be const(Slot)*. But this is silly, because now the caller isn't allowed to modify the Slot either, so now I need to bloat the code with two identical copies of findSlot, one with const, and one without (since if it wasn't marked const, then a const method couldn't call it). Is there any way to work around this? Or more importantly, why does the compiler force all internal members of this to be const inside a const method, when what it really should be enforcing is that nothing is being *modified*? What's wrong with extracting non-const members from the object in a const method, if you never actually do anything to it? T -- Never wrestle a pig. You both get covered in mud, and the pig likes it.