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 a Bar somewhere */ }
Bar* bar() {
return const_cast< Bar* >(
static_cast< const Foo* >(this)->bar());
}
};
for lots of methods like bar(). Writing these non-const methods which call the const ones by hand is tedious; besides, I feel I am repeating myself – which makes me feel bad.
What can I do to alleviate this task? (Macros and code generators are not allowed.)
Edit: Besides litb’s solution I also like my own. 🙂
Another way could be to write a template that calls the function (using CRTP) and inherit from it.
Note that the call has no performance lost: Since the member pointer is passed as a template parameter, the call can be inlined as usual.