0

I have the following const function that uses the non-const function locate. locate can not be const because it might return a reference to *this but it never changes anything in this. I would like to be able to call locate so that I am not duplicating code, so what is the right way to use this non-const functon in this case?

As you can see, I even make the result of locate a const but that doesn't guarantee that I don't change something from within locate. So is there a way to make functions temporarily constant or something?

bool SegmentNode::find(const Segment& ss) const {
    const SegmentNode& parent = locate(ss);
    for (Segment in : parent.overlap_beg()) {
        if (ss == in)
            return true;
    }
    return false;
}
jdodle
  • 141
  • 1
  • 3
  • 11
  • 1
    Just duplicate locate with the const and non-const versions. If you don't want to repeat the code, you can use the solution from here: https://stackoverflow.com/questions/856542/elegant-solution-to-duplicate-const-and-non-const-getters – LoPiTaL Jun 22 '17 at 19:26
  • @LoPiTaL, thank you, I like this solution – jdodle Jun 22 '17 at 19:39

2 Answers2

2

The solution is to have two locate functions: one is const and the other isn't. You'll use a const_cast in the non-const version, and the resulting code is legal because the entry point for SegmentNode was non-const.

const SegmentNode& SegmentNode::locate(const Segment& s) const{
  // as you have it already
  return* this;
}

SegmentNode& SegmentNode::locate(const Segment& s){
  return const_cast<SegmentNode&>(static_cast<const SegmentNode*>(this)->locate(s));
}

Demo

Obligatory edit: There should be two versions of locate anyway that account for const-ness. The solution I have above is just a way to avoid duplicating code, ugly as it is.

AndyG
  • 39,700
  • 8
  • 109
  • 143
1

Basically, you can't (although you can force a const_cast but you should not).

To assure const-correctness locate should also be const OR SegmentNode::find should not be const. To help you, ask yourself why is locate not const if it never changes anything ?

Choose whatever is more appropriate for your case.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
coincoin
  • 4,595
  • 3
  • 23
  • 47