【发布时间】:2019-02-25 16:49:10
【问题描述】:
有时我发现自己添加了具有相同实现的重载,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);
}
?
【问题讨论】:
-
好问题。绝对是重复的。一个适当的模式尚未出现。 Scott Meyers 使用
const_cast技术。