This question already has answers here:
How do I remove code duplication between similar const and non-const member functions?

(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/

10-11 22:59
查看更多