相同模板类但模板类型不同的受保护成员

我有一个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>的受保护成员。显然,不同的模板类型使编译器将其视为不同的类,因此它无法访问受保护的成员。是否有一种干净的方法允许Matrix2d<T>对象访问Matrix2d<bool>对象的受保护成员?

P.S。显然,我没有包含足够的代码来使其可编译,我只是在尝试包含关键要素。如果有人想要可编译的代码,请告诉我。

lz407854504 回答:相同模板类但模板类型不同的受保护成员

实际上,matrix2d<bool>matrix2d<int>是不相关的类型,即使它们来自同一模板。

要允许彼此访问私有成员,您可以添加: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;
    }
};
本文链接:https://www.f2er.com/2883417.html

大家都在问