Let\'s say I have the following class X
where I want to return access to an internal member:
class Z
{
// details
};
class X
{
std::vec
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.
Here's Meyers' solution (simplified):
struct C {
const char & get() const {
return c;
}
char & get() {
return const_cast(static_cast(*this).get());
}
char c;
};
The two casts and function call may be ugly but it's correct. Meyers has a thorough explanation why.