我有一個計算矩陣行列式的函式。我的矩陣類是這樣的:
template <int Col, int Row, typename T>
class Matrix;
我已經為Mat<1, 1, T>, Mat<2, 2, T>,實作了 3 個特定功能Mat<3, 3, T>:
template <typename T>
float Determinant(const Matrix<1, 1, T>& mat);
template <typename T>
float Determinant(const Matrix<2, 2, T>& mat);
template <typename T>
float Determinant(const Matrix<3, 3, T>& mat);
現在我想要一個函式來計算那些維度高于 3x3 的矩陣的行列式。我試影像這樣實作它:
template <int Dim, typename T>
float Determinant(const Matrix<Dim, Dim, T>& mat)
{
float result = 0;
for (int i = 0; i < Dim; i)
{
// This function return a minor matrix of `mat`
Matrix<Dim - 1, Dim - 1, T> minor = mat.GetMinorMatrix(i, 0);
result = (i & 1 ? -1 : 1) * mat(i, 0) * Determinant(minor);
}
}
// I try to use that function
Matrix<1, 1, float> mat { 1.0f };
Determinant(mat); // Error occurred here
但不知何故,當我嘗試構建該代碼時,我的編譯器不斷崩潰。我的 IDE 報告了這個錯誤:In template: recursive template instantiation exceeded maximum depth of 1024. 當我洗掉該功能時,該錯誤將消失template <int Dim, typename T> float Determinant(const Matrix<Dim, Dim, T>& mat)。為什么會發生該錯誤,我該如何解決?
uj5u.com熱心網友回復:
想象一下你Determinant用Dim = 0. 您的編譯器將嘗試實體化Determinant<-1>,然后再實體化Determinant<-2>,依此類推。在某個時候,您將達到最大值 1024。一個最小的可重現示例可能如下所示:
template <int I>
void foo() {
foo<I - 1>();
}
int main() {
foo<5>();
}
您可以通過不同的方式解決此問題。更現代的方法將檢查最終的遞回呼叫:
template <int I>
void foo() {
if constexpr (I > 0) {
foo<I - 1>();
} else {
// however you want to deal with I = 0
}
}
或者通過使用模板模式匹配:
template <int I>
void foo() {
foo<I - 1>();
}
template <>
void foo<0>() {
// however you want to deal with I = 0
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/507840.html
上一篇:Sqlserver余額表更新遞回
