假设我有以下 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。
这是 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/