C++ Best way to have class member which is a pointer (or reference) to another class and can handle both const and non-const situations

不想你离开。 提交于 2021-02-11 12:42:48

问题


Consider the following sample code. It compiles and works as expected. However, if I add "const" to the beginning of the first line of main function, it will not compile, because B class takes a pointer to A, and with const being added, we will have a pointer to const A instead. Templatizing B is an option, but I wonder if there are cleaner/nicer solutions for this. I am open to various suggestions, including moving the B inside A if that would help (B is used by A only).

#include <vector>

template <typename T>
class B;

template <typename T>
class A{
  friend class B<T>;

  std::vector<T> data;

public:
  A(int n) {
    data.resize(n); for (int i = 0; i < n; i++)
      data[i] = static_cast<T>(i);
  }
  B<T> getB(int pos) {return B<T>(this, pos);}
  const B<T> getB(int pos) const {return B<T>(this, pos);}
};

template <typename T>
class B {
    A<T>* pointerToA;
    int pos;
  public:
    B(A<T>* pointerToA_, int pos_) : pointerToA(pointerToA_), pos(pos_) {}
    T& get() const { return pointerToA->data[pos]; }
    T& get() { return pointerToA->data[pos]; }
  };

int main() {
  A<int> a(10); // const A<int> a(10); will not compile!
  int& i = a.getB(3).get();
}

来源:https://stackoverflow.com/questions/65286216/c-best-way-to-have-class-member-which-is-a-pointer-or-reference-to-another-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!