首页 > 解决方案 > 如何为非常量和常量重载实现一次成员函数?

问题描述

有时我发现自己添加了具有相同实现的重载,其中constin 限定符和返回值是唯一的区别:

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);
}

?

标签: c++constants

解决方案


斯科特迈耶斯的建议:

当 const 和 non-const 成员函数具有基本相同的实现时,可以通过让 non-const 版本调用 const 版本来避免代码重复。


推荐阅读