递归调用模板化函数 (C++)

Calling Templated Function Recursively (C++)

本文关键字:C++ 函数 调用 递归      更新时间:2023-10-16

我正在编写一个模板化的数学矩阵类来习惯一些新的 c++11 功能,基本声明如下:

template <typename Type, int kNumRows, int kNumCols>
class Matrix { ... };

该类有一个成员函数来返回其次要函数之一(稍后用于计算 NxN 矩阵的行列式)。

Matrix<Type, kNumRows - 1, kNumCols - 1> minor(const int row, const int col) {
  static_assert(kNumRows > 2, "");
  static_assert(kNumCols > 2, "");
  ...
}

然后,我创建了一个非成员函数来计算任何方阵的行列式:

template <typename Type, int kSize>
Type determinant(const Matrix<Type, kSize, kSize>& matrix) {
  switch (kSize) {
  case 2:
    return 0; // For now unimportant
  case 3:
    // Recursively call the determinant function on a minor matrix
    return determinant(matrix.minor(0, 0));
  }
  ...
}

在main()中,我创建了一个3x3矩阵并在其上调用determinant这不会编译。编译器有效地移动到案例 3,创建一个次要矩阵并对其调用 determinant然后,它再次进入case 3,通过尝试创建 1x1 次要元素导致static_assert。

问题很简单:我在这里错过了什么吗?像这样递归地调用模板化函数是根本不允许的吗?这是编译器的错误(我对此表示怀疑)?

为了完整起见:我正在使用Clang++。

模板确定在编译时要做什么,但switch语句确定在运行时要做什么。 编译器为所有开关情况生成代码,或至少验证有效性,即使在编译时正确的情况是"显而易见的"。

不要使用 switch ,请尝试重载行列式:

template <typename Type>
Type determinant(const Matrix<Type, 1, 1>& matrix) {
    return matrix(0,0);
}
template <typename Type>
Type determinant(const Matrix<Type, 2, 2>& matrix) {
    return 0; // (incorrect math)
}
template <typename Type, int kSize>
Type determinant(const Matrix<Type, kSize, kSize>& matrix) {
    return determinant(matrix.minor(0,0)); // (incorrect math)
}

编译器生成所有代码路径,即使这些路径在执行期间并未全部访问(实际上可能会在优化步骤中删除)。因此,determinant<Type, kSize - 1, kSize - 1>始终被实例化,即使对于kSize <3也是如此。

您需要

部分专用化您的函数以防止这种情况,您需要适当地重载您的determinant函数:

template <typename Type>
Type determinant(const Matrix<Type, 2, 2>& matrix) {
  ...
}

顺便说一下,这使得函数中的switch语句变得多余。

您需要在编译时使用模板专用化进行切换:

template <typename Type, int kSize>
struct Determinate {
    Type operator()(const Matrix<Type, kSize, kSize>& matrix) const {
        // Recursively call the determinant function on a minor matrix
        return Determinate<Type, kSize-1>{}(matrix.minor(0, 0));
    }
};
template <typename Type>
struct Determinate<Type, 2> {
    Type operator()(const Matrix<Type, kSize, kSize>& matrix) const {
        return 0; // For now unimportant
    }
};
template <typename Type, int kSize>
Type determinant(const Matrix<Type, kSize, kSize>& matrix) {
    return Determinate<Type, kSize>{}(matrix);
}