How to generate a non-const method from a const method?

c++, const-correctness, dry

Solution

Another way could be to write a template that calls the function (using CRTP) and inherit from it.

template<typename D>
struct const_forward {
protected:
  // forbid deletion through a base-class ptr
  ~const_forward() { }

  template<typename R, R const*(D::*pf)()const>
  R *use_const() {
    return const_cast<R *>( (static_cast<D const*>(this)->*pf)() );
  }

  template<typename R, R const&(D::*pf)()const>
  R &use_const() {
    return const_cast<R &>( (static_cast<D const*>(this)->*pf)() );
  }
};

class Bar;

class Foo : public const_forward<Foo> {
public:
  const Bar* bar() const { /* code that gets a Bar somewhere */ }
  Bar* bar() { return use_const<Bar, &Foo::bar>(); }
};

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.

Problem

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. :)

Original source