c++ - 如何删除类似的 const 和非常量成员函数之间的代码重复?

标签 c++ class constants code-duplication c++-faq

假设我有以下 class X 我想在其中返回对内部成员的访问权限:

class Z
{
    // details
};

class X
{
    std::vector<Z> vecZ;

public:
    Z& Z(size_t index)
    {
        // massive amounts of code for validating index

        Z& ret = vecZ[index];

        // even more code for determining that the Z instance
        // at index is *exactly* the right sort of Z (a process
        // which involves calculating leap years in which
        // religious holidays fall on Tuesdays for
        // the next thousand years or so)

        return ret;
    }
    const Z& Z(size_t index) const
    {
        // identical to non-const X::Z(), except printed in
        // a lighter shade of gray since
        // we're running low on toner by this point
    }
};

两个成员函数 X::Z()X::Z() const 在大括号内具有相同的代码。这是重复代码可能会导致逻辑复杂的长函数出现维护问题

有没有办法避免这种代码重复?

最佳答案

有关详细说明,请参阅第 10 页的标题“避免 const 和非 const 成员函数中的重复”。 23,在第 3 项“尽可能使用 const”中,在 Effective C++, 3d ed作者:Scott Meyers,ISBN-13:9780321334879。

alt text

这是 Meyers 的解决方案(简化版):

struct C {
  const char & get() const {
    return c;
  }
  char & get() {
    return const_cast<char &>(static_cast<const C &>(*this).get());
  }
  char c;
};

这两个强制转换和函数调用可能很难看,但在非 const 方法中是正确的,因为这意味着该对象一开始就不是 const。 (迈耶斯对此进行了彻底的讨论。)

关于c++ - 如何删除类似的 const 和非常量成员函数之间的代码重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/123758/

相关文章:

c++ - OpenCL - 我的数组怎么会太大而导致堆栈溢出?

java - 在将类的变量存储在java中之前对其进行加密

c# - 常量声明如何设置为自身工作

php - PHP 应用程序应该将配置数据存储在定义的常量还是数据库中?

c++ - 如何在 C++ win32 API 的对话框中设置图像?

c++ - 如何覆盖CMake中的宏定义

c++ - sprintf - 字符串前有 4 个无用的 ascii 字符

python - 如何从继承字符串类型的新类访问字符串值

java - Jaws Wordnet 的编译问题

c++ - 如何为集合提供带有迭代器的 const 接口(interface)?