gpt4 book ai didi

C++ Eigen 库 : Cast for fixed sized Matrices

转载 作者:行者123 更新时间:2023-11-30 01:06:13 27 4
gpt4 key购买 nike

以下问题:

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 兼容的方法!

最佳答案

您可以使用 constexpr if从 C++17 开始,根据条件的值,如果值为 true,则丢弃 statement-false(如果存在),否则丢弃 statement-true;那么代码不会导致编译错误。例如

template<int nDim>
void foo () {

Eigen::Matrix<double, nDim, nDim> bar;

if constexpr ( nDim == 3 ) {
bar = generate_a_special_3x3_Matrix();
} else constexpr if ( nDim == 2 ) {
bar = generate_a_special_2x2_Matrix();
}

// ... further math here
}

或者制作一个generate_a_special_Matrix函数模板,例如

template <int nDim>
Eigen::Matrix<double, nDim, nDim> generate_a_special_Matrix();

template <>
Eigen::Matrix<double, 2, 2> generate_a_special_Matrix<2>() {
... generating ...
return ...;
}

template <>
Eigen::Matrix<double, 3, 3> generate_a_special_Matrix<3>() {
... generating ...
return ...;
}

然后

template<int nDim>
void foo () {

Eigen::Matrix<double, nDim, nDim> bar;
bar = generate_a_special_Matrix<nDim>();

// ... further math here
}

关于C++ Eigen 库 : Cast for fixed sized Matrices,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46772947/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com