c++ - 如何为非 const 和 const 重载实现一次成员函数?

标签 c++ constants

<分区>

有时我发现自己添加了具有相同实现的重载,只是限定符中的 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 的建议:

When const and non-const member functions have essentially identical implementations, code duplication can be avoided by having the non-const version call the const version.

关于c++ - 如何为非 const 和 const 重载实现一次成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52440969/

相关文章:

c++ - 获取唯一编号并知道它们何时被释放

包含枚举的结构的 C++ 复制构造函数

c++ - 未遵循 std::function const 正确性

c++ - 在 C++ 中使用 const 引用参数访问函数成员的最佳实践

c# - 将局部变量声明为 const

c++ - 在 C++ 中的线程之间共享列表

c++ - 如何让我完成的程序通过终端输入读取文件?

c++ - 这段代码有什么问题,它崩溃了

c++ - 将元组的 const 引用传递给仿函数

无法在 C 中为 "const char * const *my_array"赋值