我有一个 Matrix2d
模板类和每个 Matrix2d
对象是 std::vector
在引擎盖下。我经常访问std::vector
直接在速度和简单的方法中。当我试图重载 operator ==
时遇到了一个问题使其进行逐个元素的比较并使其返回 Matrix2d<bool>
.
template <class T>
class Matrix2d {
protected:
std::vector<T> vec;
public:
Matrix2d<bool> operator==(const Matrix2d<T>& rhs) const
{
Matrix2d<bool> mat(numRows, numCols);
for (unsigned index=0; index<vec.size(); index++) {
mat.vec[index] = vec[index] == rhs.vec[index];
}
return mat;
}
};
问题是
Matrix2d<T>
对象无法访问 Matrix2d<bool>
的 protected 成员.显然不同的模板类型使编译器认为它是一个不同的类,因此它不能访问 protected 成员。有没有允许Matrix2d<T>
的干净方法?访问 Matrix2d<bool>
的 protected 成员的对象对象?附言显然,我没有包含足够的代码来使其可编译,我只是试图包含关键元素。如果有人想要可编译的代码,请告诉我。
最佳答案
确实,matrix2d<bool>
和 matrix2d<int>
是不相关的类型,即使它们来自同一个模板。
要允许彼此访问私有(private)成员,您可以添加:template <typename U> friend class Matrix2d;
.
您可能只为 matrix2d<bool>
这样做,但我怀疑它会产生太多重复。
template <class T>
class Matrix2d {
protected:
std::vector<T> vec;
std::size_t numRows;
std::size_t numCols;
public:
template <typename U> friend class Matrix2d;
Matrix2d(std::size_t numRows, std::size_t numCols);
Matrix2d<bool> operator==(const Matrix2d<T>& rhs) const
{
Matrix2d<bool> mat(numRows, numCols);
for (unsigned index=0; index<vec.size(); index++) {
mat.vec[index] = vec[index] == rhs.vec[index];
}
return mat;
}
};
关于c++ - 相同模板类但不同模板类型的 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59430903/