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/