This question already has answers here:
How do I remove code duplication between similar const and non-const member functions?
(19个回答)
2年前关闭。
有时我发现自己添加了具有相同实现的重载,其中qualt中的
有没有一种惯用的方法来只编写一次实现并摆脱比
?
(19个回答)
2年前关闭。
有时我发现自己添加了具有相同实现的重载,其中qualt中的
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)的建议:
关于c++ - 如何一次实现非const和const重载的成员函数? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52440969/