Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force preference of const-version?

Tags:

c++

let's say I have

class A {
  double a;
  double Value() const {
    return a;
  }

  double& Value() {
    return a;
  }

}

//later:
A foo;
double b = foo.Value();

now, the non-const version will be called. Is there a nice way to force the use of the const version? I think it's possible with a cast but I don't think it's very elegant.

like image 699
lezebulon Avatar asked Dec 16 '22 10:12

lezebulon


1 Answers

You may cast it to const.

double b = static_cast<const A&>(foo).Value();

(I don't think I've ever explicitly added const to a variable. I'm not sure if static_cast is more appropriate than const_cast.)

like image 151
Drew Dormann Avatar answered Jan 04 '23 16:01

Drew Dormann