以下问题:
template<int nDim>
void foo ( ){
Eigen::Matrix<double, nDim, nDim> bar;
if ( nDim == 3 ){
bar = generate_a_special_3x3_Matrix();}
else if ( nDim == 2 ){
bar = generate_a_special_2x2_Matrix();}
// ... further math here
}
因此,当然由于静态断言,此代码无法编译。
但是,可以保证在运行时不会发生任何问题。
当前已知的解决方案是通过.block(3,3)或通过Ref (参见Cast dynamic matrix to fixed matrix in Eigen)进行的赋值。
.block方法:
template<int nDim>
void foo ( ){
Eigen::Matrix<double, nDim, nDim> bar;
if ( nDim == 3 ){
bar.block(3,3) = generate_a_special_3x3_Matrix();}
else if ( nDim == 2 ){
bar.block(2,2) = generate_a_special_2x2_Matrix();}
// ... further math here
}
但是,这两种方法都涉及对正确的矩阵大小进行运行时检查,这并不是真正必要的,并且编写的代码也不是很漂亮。
我并不是很在意运行时的开销(尽管最好避免它),但是在我看来,编写的代码并不是很干净,因为.block()的意图不会立即被其他人理解。
是否有更好的方法,例如像 Actor 一样?
编辑:发布了两个很好的解决方案(如果constexpr),但是,我需要一种C++ 11/14兼容的方法!
最佳答案
要优雅地使用c++ 98,可以使用comma initializer语法:
template<int N>
void foo(){
Eigen::Matrix<double, N, N> bar;
if(N==3) bar << Matrix3d();
else if(N==2) bar << Matrix2d();
}
关于c++ - C++特征库:转换为固定大小的矩阵,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46772947/