【问题标题】:Template operator of a template class requires access to other specialisations模板类的模板运算符需要访问其他特化
【发布时间】:2013-11-22 13:41:43
【问题描述】:

我已经使用 CRTP 实现了一个矩阵类。对于矩阵乘法,我想使用friend operator*。问题是,根据this question和我自己的经验,我需要在类里面定义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 错误的访问冲突?

【问题讨论】:

    标签: c++ templates friend crtp


    【解决方案1】:

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

    【讨论】:

    • 嗯,是的,但是常规元素访问函数会检查索引是否越界访问,我想在这里避免这种情况。另外,这应该是可能的,对吧?
    • 只做 std::vector 所做的事情:提供一个检查边界的访问器(std::vector::at()),以及一个不检查边界的访问器(在矢量情况下为operator[],但是您需要为多个维度使用括号)。
    • 为什么,是的,谢谢,这是个好主意。不过,如果我的问题存在的话,看看我的问题的答案会很有趣!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多