【问题标题】:template recursion when I use the non-type parameter使用非类型参数时的模板递归
【发布时间】:2021-07-27 10:41:03
【问题描述】:

我想写一个矩阵类。但是当我想处理行列式函数时,我遇到了麻烦。错误是行列式(下一个)。

template<typename T, int row, int column>
T determinant(const Mat<T, row, column>& current)
{
    if (row == 1) return current[0][0];
    if (row == 2) return current[0][0] * current[1][1] - current[0][1] * current[1][0];
    T sum = 0;
    for (int i = 0; i <= row - 1; i++)
    {
        T sign = 1;
        if (i % 2 == 1) sign = -sign;
        Mat<T, row -1, column - 1> next;
        for (int j = 0, nextRow = 0; j <= row - 1; j++)
        {
            if (i == j) continue;
            for (int k = 0; k <= row - 2; k++)
            {
                next[nextRow][k] = current[j][k + 1];
            }
            nextRow++;
        }
        sum += sign * current[i][0] * determinant(next);
    }
    return sum;
}

【问题讨论】:

  • 错误是什么?你怎么称呼这段代码?
  • 他可能达到了编译器递归限制。 @user15839305 请提供minimal reproducible example,您可以使用this
  • 我尝试重现问题,但根据 C++,您会遇到不同的问题。在 C++17 之前,在这种情况下,您需要部分特化才能进行递归,并且只有类可以这样做。在 C++17 的情况下,您需要在各个位置使用 constexpr 关键字..
  • 不相关:计算行列式的方式非常低效,仅适用于相当小的矩阵。
  • 其实是错误的实现。

标签: c++ templates recursion


【解决方案1】:

我认为您的问题可能与模板递归有关。没有什么能阻止编译器创建无效的 Matrix 类。我认为编译器不会在编译时评估 if 语句。

Mat<T, 0, 0> next;

您可以尝试矩阵类的特化。这将在编译时停止模板递归。

template<class T, unsigned int rows, unsigned int column>
Mat
{
   public:
   Det()
   {
      //Do recursion and decrement rows
   }
   protected:
   T Data[row][column];
}



template<class T, unsigned int column>
Mat<T,2,column>
{
   public:
   Det()
   {
      return Data[0][0] * Data[1][1] - Data[0][1] * Data[1][0];
   }
   protected:
   T Data[2][column];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-18
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多