设计两个等效的成员函数,分别返回一个 const 和一个非常量指向成员的指针

Designing two equivalent member functions returning a const and a non-const pointer-to-member, respectively

我有一个classA和一个成员函数f,那个returns指向 实例的一些内容

int* A::f() {
  // common code ...
  return &(this->some_container[some_index])
}

现在,我需要一个模拟函数,它只有 returns 一个 const 指针, 即

const int* A::f_const() const {
  // exactly the same lengthy code ...
  return &(this->some_container[some_index]);
}

请注意,由于 "lengthy code" 不会更改 A 的实例, 这也使得函数 const w.r.t。实例(第二个 const 语句)。

我的问题:现在我想知道是否有一些解决方案可以避免代码 加倍,不使用第三个函数

一方面,在 f_const 中调用 f 是非法的,因为 f 不是 constw.r.t。拥有的实例。另一方面,调用 f_const f 内部需要将 const 指针转换为非 const 指针,这也是不可能的。

有没有什么优雅的声明方式,避免代码重复?

如前所述,使用具有 ff_const 在这里不是一个选项,因为当申请大量 函数,这会使代码的可读性降低。

我想假设答案可能取决于特定的上下文(例如函数的长度代码、返回的类型等...)。

总的来说,根据我的经验,最实用的解决方案是 const cast operator.

只是为了实现const方法,在non-const其他方法中转换得到。类似于:

const int* A::f_const() const {
  return &(this->some_container[some_index]);
}

int* A::f() {
  return const_cast<int*>(f_const());
}

这通常是安全的,因为您是 class 本身的设计者。