While striving for const-correctness, I often find myself writing code such as this
class Bar;
class Foo {
public:
const Bar* bar() const { /* code that gets
Use following trick:
class Bar;
class Foo {
public:
Bar* bar() {
// non-const case
/* code that does something */
}
const Bar* bar() const {
return This().bar(); // use non-const case
}
private:
//trick: const method returns non-const reference
Foo & This() const { return const_cast(*this); }
};
Note it is possible to use unique function This
for any const/non-const functions.
Alternative solution without static_cast (but I prefer the first one):
class Bar;
class Foo {
public:
const Bar* bar() const { /* code that does something */ }
Bar* bar() { return const_cast(cthis().bar()); } // use const case
private:
const Foo & cthis() const { return *this; }
};