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<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.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…