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

Eigen: function signature which accepts general matrix expression of fixed size and type

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

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

使用 MatrixBase 而不是 Matrix 的原因是所有稠密特征矩阵表达式都派生自 MatrixBase。因此,例如,如果我传递一个矩阵块

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 必须先将块类型转换为矩阵,然后再将其传递给函数,这意味着必须创建一个不必要的临时对象。

理解有误请指正...

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

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

为了完整起见,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;
}