Okay, I did some research and apparently there are a lot of duplicate questions on SO on this topic, to name a few:
- Elegant solution to duplicate, const and non-const, getters?
- How to avoid operator's or method's code duplication for const and non-const objects?
- How do I remove code duplication between similar const and non-const member functions?
etc. But I cannot help but raise this again, because
- With c++14
auto
-typed return value, I am literally duplicating the function body with the only difference being theconst
function qualifier. - It is possible that
const
version and non-const
version may return types that are totally incompatible from each other. In such cases, neither Scott Meyers'sconst_cast
idiom, nor the "privateconst
function returning non-const
" technique would work.
As an example:
struct A {
std::vector<int> examples;
auto get() { return examples.begin(); }
auto get() const { return examples.begin(); }
}; // Do I really have to duplicate?
// My real-world code is much longer
// and there are a lot of such get()'s
In this particular case, auto get()
returns an iterator
while auto get() const
returns a const_iterator
, and the two cannot be converted into each other (I know erase(it,it)
trick does the conversion in this case but that's not the point). The const_cast
hence does not work; even if it works, that requires the programmer to manually deduce auto
type, totally defeating the purpose of using auto
.
So is there really no way except with macros?