c++ - Eigen:接受固定大小和类型的通用矩阵表达式的函数签名

标签 c++ eigen eigen3

Eigen 文档中充满了说明应该如何编写接受矩阵的通用函数的示例:

template <typename Derived>
void print_cond(const MatrixBase<Derived>& a)

使用原因 MatrixBase而不是 Matrix是所有密集的特征矩阵表达式都来自 MatrixBase .因此,例如,如果我传递一个矩阵 block

print_cond ( A.block(...));

然后使用签名 const MatrixBase<Derived>& a避免创建一个临时的。相反,如果我们用签名声明函数

template <typename T, int rows, int cols>
void print_cond(const Matrix<T,rows,cols>& a)

那么 Eigen 必须先将 block 类型转换为矩阵,然后再将其传递给函数,这意味着必须创建一个不必要的临时对象。

如果理解有误,请指正...

考虑到这一点,第二种方法的好处之一是我们可以在编译时检查矩阵的维度(假设它们是固定的,而不是动态的)。

我在文档中找不到的是第一种方法的通用示例(这有助于避免临时创建),但它对矩阵的类型和维度进行了编译时间检查。有人可以告诉我该怎么做吗?

最佳答案

为了完整起见,Marc 和 ggael 建议这样

#include <iostream>
#include "Eigen/Dense"

using namespace Eigen;

using T = double;

const int rows = 5;
const int cols = 3;

template<typename Derived>
void print_cond(const MatrixBase <Derived> &a) {

    /* We want to enforce the shape of the input at compile-time */
    static_assert(rows == Derived::RowsAtCompileTime);
    static_assert(cols == Derived::ColsAtCompileTime);

    /* Now that we are guaranteed that we have the
     * correct dimensions, we can do something... */
    std::cout << a;
}

int main() {
    print_cond(Matrix<T, rows, cols>::Ones());

    /* These will not compile */
    // print_cond(Matrix<T, rows + 1, cols>::Ones());
    // print_cond(Matrix<T, rows, cols + 1>::Ones());
    // print_cond(Matrix<T, rows + 1, cols + 1>::Ones());
    return 0;
}

关于c++ - Eigen:接受固定大小和类型的通用矩阵表达式的函数签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48974503/

相关文章:

C++ Eigen : How to write a function that can both take a regular (dense) Matrix, 还是 DiagonalMatrix?

c++ - 使用 Visual Studio 构建 QT

C++ 多重继承从文件保存对象中读取两次

c++ - 带有复制构造函数的多态性

c++ - 使用Eigen库进行sparseLU并显示L&U?

C++ Eigen 稀疏矩阵乘法比 python scipy.sparse 慢得多

c++ - 将特征矩阵映射到 C 数组

c++ - 如何使用 Eigen 库计算矩阵的右核?

c++ - Eigen::Ref<> 作为成员变量

c++ - 借助 static_assert 改进诊断