template< typename K, typename T >
class HashMap
{
...
private:
bool locate( Key a_Key, Bucket *& a_pBucket ); // Used in the 'add' and 'remove' methods.
bool locate( Key a_Key, Bucket const *& a_pBucket ) const; // Used in the 'contains' method.
...
};
Both 'locate' methods do exactly the same.
To avoid a code duplicate I could use a gigantic macro or const_cast (so I could call the const locate method in the non-const one) but that would be hackish.
No it isn't. Why do you have 2 functions which are doing the same? Remove the non-const function and you should be happy?
I need to have 2 overloads, one const and one non-const, because that private method is called in both const (e.g. 'contains') and non-const (e.g. 'add') methods.
If I removed the non-const version I could not pass a non-const pointer to a Bucket structure as a parameter.
How about you use an iterator instead of a pointer? In that case you could always use the same locate method to find something (make it private!) and return a constant or non-constant iterator depending on what is needed.
How about you use an iterator instead of a pointer? In that case you could always use the same locate method to find something (make it private!) and return a constant or non-constant iterator depending on what is needed.
Thank you!
But I don't really get it. How can one function return both const and non-const iterators?
if I removed the non-const version I could not pass a non-const pointer to a Bucket structure as a parameter.
That's only because you're passing a reference to a non-const pointer to const Bucket.
If your function is not modifying its second argument, it should be const reference:
It doesn't really have anything to do with the iterator, I just said that cause I prefer iterators over pointers - you could do the same thing with a pointer. Basically, let the const version call the non-const version (again, I'm not sure if C++ permits this, cause I never had a situation like that), since you can always safely turn a non-const pointer into a const-pointer that'd be fine. Or you could make it return a hash instead of a pointer, if it's already a hashmap - in that case you wouldn't even need 2 versions.