-1

Consider the following code:
http://coliru.stacked-crooked.com/a/d89377889a8ff749

IStorage has const and non-const get methods.
The concrete implementation defines them, but the definition is just copy-paste.
I could not call one get method from another because of the const mechanics of C++.

Is there any way to avoid this copy-paste?

Vladimir Tsyshnatiy
  • 877
  • 1
  • 9
  • 19
  • 2
    dupe of [How do I remove code duplication between similar const and non-const member functions?](https://stackoverflow.com/questions/123758/how-do-i-remove-code-duplication-between-similar-const-and-non-const-member-func) (also, please post code in the q, not linked externally) – underscore_d Feb 05 '21 at 09:57
  • Yep, that is the dupe. Is there any way to remove this question? I can not see the button. – Vladimir Tsyshnatiy Feb 05 '21 at 10:07
  • If two more users mark it as a duplicate, it'll be closed as such, otherwise there might be a "Delete" link under your question, although I don't think it'll work as someone has answered. – underscore_d Feb 05 '21 at 10:10

1 Answers1

2

This is one of the legitmate uses of const_cast

const std::string* get(ID id) const override
{
    return const_cast<ConcreteStorage*>(this)->get(id);
}
john
  • 71,156
  • 4
  • 49
  • 68