问题
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