(注意:在没有 C++0x 标志、外部限制的 GCC 4.6 上工作。我也对 C++11 和/或更新的编译器会发生什么很感兴趣)
我有一个模板类,用于对固定大小的矩阵进行操作:
template<size_t rows, size_t cols, class Type>
class MatrixFixed;
在那个类中,我定义了一个具有以下方面的“移位”操作:
template<size_t rows, size_t cols, class Type>
template<size_t numRowsUp>
MatrixLogicalFixed<rows,cols,Type> MatrixLogicalFixed<rows,cols,Type>::shiftUp( const Type & filler ) const
{
if( (numRowsUp>=rows) )
{
return MatrixLogicalFixed<rows,cols,Type>(filler);
}
else
{
MatrixLogicalFixed<numRowsUp,cols,Type> temp(filler);
return this->getSubMatrix<rows-numRowsUp,cols>( numRowsUp, 0 )
.joinV( temp );
}
}
想法是,如果要移动的位置数大于总行数,则可以返回一个填充有默认值的矩阵。
然而,在那些情况下 (numRowsUp >= rows
) 编译以 internal compiler error: in force_constant_size at gimplify.c:691 at the last code line .joinV( temp )
结束。
过程中的矩阵大小(我的猜测):
- 返回值:(行 x 列)矩阵
-
getSubMatrix<rows-numRowsUp,cols>( numRowsUp, 0 )
:当numRowsUp>=rows
,这将导致由于 size_t 下溢而产生大量数据 -
joinV
函数试图推断出适当的返回大小,但这是不可能的。
这是 joinV 声明):
template<size_t rows, size_t cols, class Type>
template<size_t rows2, size_t cols2>
MatrixLogicalFixed<rows+rows2,cols,Type> MatrixLogicalFixed<rows,cols,Type>::joinV(const MatrixLogicalFixed<rows2,cols2,Type> & B) const
自 if
条件是在编译时定义的,这是一段代码,在有问题的情况下永远不会达到。到目前为止我尝试了什么:
- 在预处理器#if 中使用模板参数——显然是错误的。
- 寻找可以解决问题的任何类型的预处理器宏 MIN 或 MAX。
通常的偏特化看起来不像是有效的解决方法,因为存在无限的值组合...我对任何类型的解决方案都持开放态度。我只想让我的类(class)编译 :D
最佳答案
预处理器 MAX 有什么问题?
您可以使用 MAX(0, rows-numRowsUp)
作为模板参数。或者试试这个作为模板参数:(numRowsUp>=rows)? 0 : 行-numRowsUp
。这样错误的模板永远不会被实例化。
关于c++ - 模板参数计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17341018/