【问题标题】:How to implement a member function once for both non-const and const overloads? [duplicate]如何为非常量和常量重载实现一次成员函数? [复制]
【发布时间】: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 技术。

标签: c++ constants


【解决方案1】:

斯科特迈耶斯的建议:

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

【讨论】:

  • 并不总是可行的:struct Counterexample { int meow() { return 42; } int meow() const { return 314; } int nyan() { return meow(); } int nyan() const { return meow(); } };
  • 同意。但它可能在 OP 上下文中很有用。
  • 所以它基本上(几乎)与我的const_cast示例相同
  • 使用了两个演员表。一种是 static_cast 将 const 添加到 *this 的类型,以便调用 const 版本。另一个是const_cast 在返回类型上抛弃const。并且这些强制转换用于非常量版本。
猜你喜欢
  • 2012-12-13
  • 2019-05-04
  • 1970-01-01
  • 1970-01-01
  • 2012-01-28
  • 2019-07-09
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
相关资源
最近更新 更多