递归调用模板化函数 (C++)
Calling Templated Function Recursively (C++)
我正在编写一个模板化的数学矩阵类来习惯一些新的 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);
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗