<分区>
有时我发现自己添加了具有相同实现的重载,只是限定符中的 const
和返回值是唯一的区别:
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;
};
有没有比 const_cast
更好的惯用方法来只编写一次实现并摆脱复制粘贴:
const B& get(int key) const
{
return const_cast<A*>(this)->get(key);
}
?