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
Another way could be to write a template that calls the function (using CRTP) and inherit from it.
template
struct const_forward {
protected:
// forbid deletion through a base-class ptr
~const_forward() { }
template
R *use_const() {
return const_cast( (static_cast(this)->*pf)() );
}
template
R &use_const() {
return const_cast( (static_cast(this)->*pf)() );
}
};
class Bar;
class Foo : public const_forward {
public:
const Bar* bar() const { /* code that gets a Bar somewhere */ }
Bar* bar() { return use_const(); }
};
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.