模板类的模板操作员需要访问其他专业

Template operator of a template class requires access to other specialisations

本文关键字:其他 访问 操作员      更新时间:2023-10-16

我已经使用CRTP实现了一个矩阵类。对于矩阵乘法,我想使用friend operator*。问题是,根据这个问题和我自己的经验,我需要在类中定义operator*才能使其工作。

然而,这意味着我必须重新使用定义中的类模板参数,这只允许访问计算中涉及的三个矩阵中的一个。我似乎无法为别人提供友谊。

代码示例:

template<template<unsigned, unsigned> class Child, unsigned M, unsigned N>
class BaseMatrix
{
    // This works, but does not give access to rhs or to the return value
    template<unsigned L>
        friend Child<M, L> operator*(const BaseMatrix<Child, M, N>& lhs, const BaseMatrix<Child, N, L>& rhs)
    {
        Child<M, L> result;
        result.v = lhs.v + rhs.v; // demo, of course
        return result;
    }
    // This compiles, but does not do anything
    template<template<unsigned, unsigned> class Child2, unsigned M2, unsigned N2, unsigned L>
        friend Child2<M2, N2> operator*(const BaseMatrix<Child2, M2, L>&, const     BaseMatrix<Child2, L, N2>&);
    // This produces an ambiguous overload
    template<unsigned L>
        friend Child<M, N> operator*(const BaseMatrix<Child, M, L>& lhs, const     BaseMatrix<Child, L, N>& rhs);
    double v;
};
template<unsigned M, unsigned N>
class ChildMatrix : public BaseMatrix<ChildMatrix, M, N>
{
};

int main()
{
    ChildMatrix<3, 4> a;
    ChildMatrix<4, 5> b;
    ChildMatrix<3, 5> c = a * b;
    return 0;
}

如何在此处防止对rhs.vresult.v的访问冲突错误?

不要为此使用friend。矩阵类应该单独公开其元素,这足以从正则(非友元)函数中进行乘法运算。