How do I remove code duplication between similar const and non-const member functions?

For a detailed explanation, please see the heading “Avoid Duplication in const and Non-const Member Function,” on p. 23, in Item 3 “Use const whenever possible,” in Effective C++, 3d ed by Scott Meyers, ISBN-13: 9780321334879.

alt text

Here’s Meyers’ solution (simplified):

struct C {
  const char & get() const {
    return c;
  }
  char & get() {
    return const_cast<char &>(static_cast<const C &>(*this).get());
  }
  char c;
};

The two casts and function call may be ugly, but it’s correct in a non-const method as that implies the object was not const to begin with. (Meyers has a thorough discussion of this.)

Leave a Comment