以下问题:C++库的本征:投给固定大小的矩阵
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)或通过参考< ..>(参见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()的意图不会立即清除其他人。 有没有更好的方法,例如像一个演员?
编辑:两个很好的解决方案发布(如果constexpr),但是,我需要一个C++ 11/14兼容的方法!
本案例中的完美解决方案!谢谢! – macmallow