I had no success finding help on the web, but I also have some trouble to concisely define my problem, so I'll start with the code:
const cHalfEdge* cHalfEdge::prev() const
{
const cHalfEdge* result = nullptr;
if (next_ != nullptr) {
const cHalfEdge* current = this;
while (current->next_ != nullptr && current->next_ != this) {
current = current->next_;
}
if (current->next_ == this)
result = current;
}
return result;
}
cHalfEdge* cHalfEdge::prev()
{
const cHalfEdge* result = (const cHalfEdge*)(this)->prev();
return const_cast<cHalfEdge*>(result);
}
As you can see, I have two overloaded versions of the same function, that differ only in their respective const qualifier. I deliberately made two functions to ensure const-correctness. Since the implementation is the same however, I want it to be in only one place.
Now the problem arises that I cannot easily call one version from the other. In the code above, I did a small hack to force the call of the other version, and even though I haven't even run the program yet, I am sure that it works. Still, the compiler (VC10.0) issues a warning, claiming that this function will cause an endless recursion.
I realize there are other possible solutions, e. g. to move the implementation to a function with a different name. But
that is not the problem I wish to discuss.
I always try to avoid type casts, and that first one is particularly ugly. I wondered if it is really necessary - And that is where my question arises:
Is it possible to specifically call the const version of an overloaded function without casting the object I'm calling it on to const?
Edit:
After improving the wording of my question and trying another search, I've found a similar discussion here:
http://stackoverflow.com/questions/5620071/how-do-i-call-overloaded-member-function-with-cv-qualifier[
^]
Looks like it is indeed necessary to const-cast the object (
this
, in this case). Pity, I would have hoped for a more elgant solution.