Sometimes I find myself adding overloads that have the same implementation, with const
in qualifier and return value being the only difference:
struct B {};
struct A {
const B& get(int key) const
{
if (auto i = map.find(key); i != map.end())
return i->second;
throw std::runtime_error{""};
}
B& get(int key)
{
if (auto i = map.find(key); i != map.end())
return i->second;
throw std::runtime_error{""};
}
private:
std::unordered_map<int, B> map;
};
Is there an idiomatic way to write the implementation only once and get rid of copy-paste that is better than const_cast
:
const B& get(int key) const
{
return const_cast<A*>(this)->get(key);
}
?