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 theconstfunction qualifier. - It is possible that
constversion and non-constversion may return types that are totally incompatible from each other. In such cases, neither Scott Meyers'sconst_castidiom, nor the "privateconstfunction 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?
::const_iterator != const ::iteratorconstand non-constversions, but I'd say that's a rather uncommon case, out of iterators (although I may be wrong). Not sure if it's possible to work out a general solution but maybe you could have a function to convertconst_iteratortoiterator(sayunconst_iterator) and have a pattern likeauto get() { return unconst_iterator(example, static_cast<const A &>(*this).get()); }.iteratorbut something very close (two similar classes, one withconstmembers). I could indeed write a type conversion between the two. Thanks for the advice, yet still hopefully awaiting more elegant answers.