调整大小的解决方法 Eigen::Ref

Workaround for resizing Eigen::Ref

我想使用 Eigen::Ref 来获得使用 Eigen::Matrix 参数的非模板函数。我的问题是,在这些函数中,我可能必须调整 Eigen::Ref 引用的矩阵的大小。我知道一般来说 Eigen::Ref 不应该调整大小,因为它可以映射到表达式或矩阵块,但就我而言,我确信 Eigen::Ref 后面的是 Eigen::Matrix.

为了说明这一点:

#include "Eigen/Dense"

void add(Eigen::Ref<Eigen::MatrixXd> M, const Eigen::Ref<const Eigen::MatrixXd> &A, const Eigen::Ref<const Eigen::MatrixXd> &B) {
  M=A+B;
}

int main() {
  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor, 32, 32> M(2,3);
  Eigen::Matrix<double, 2, 2> A;
  Eigen::Matrix<double, 2, 2> B;

  add(M,A,B);
}

运行时给出:

void Eigen::DenseBase<Derived>::resize(Eigen::Index, Eigen::Index) [with Derived = Eigen::Ref<Eigen::Matrix<double, -1, -1> >; Eigen::Index = long int]: Assertion `rows == this->rows() && cols == this->cols() && "DenseBase::resize() does not actually allow to resize."' failed.

我试过作弊:

void add(Eigen::Ref<Eigen::MatrixXd> M, const Eigen::Ref<const Eigen::MatrixXd> &A, const Eigen::Ref<const Eigen::MatrixXd> &B) {
  Eigen::Ref<Eigen::Matrix<double,2,2>> MM(M);
  MM=A+B;
}

但我在运行时得到:

Eigen::internal::variable_if_dynamic<T, Value>::variable_if_dynamic(T) [with T = long int; int Value = 2]: Assertion `v == T(Value)' failed.

那么,我该如何处理呢?在 Eigen 文档中,使用 MatrixBase 作为参数的模板函数解决了调整大小的问题,但 Eigen::Ref?

这是一个使用成员函数指针和粗暴转换的 hacky 解决方案:

#include <iostream>
#include <Eigen/Core>
template<class MatrixType>
struct ResizableRef
{
    typedef typename MatrixType::Scalar Scalar;
    class MatrixDummy;
    typedef void (MatrixDummy::*ResizeFunctor)(Eigen::Index rows, Eigen::Index Cols);
    typedef Scalar* (MatrixDummy::*DataGetter)();

    MatrixDummy *m;
    const ResizeFunctor resizer;
    const DataGetter getData;

    template<class Derived>
    ResizableRef(Eigen::MatrixBase<Derived>& M)
      : m(reinterpret_cast<MatrixDummy*>(&M))
      , resizer(reinterpret_cast<ResizeFunctor>((void (Derived::*)(Eigen::Index, Eigen::Index)) &Derived::resize))
      , getData(reinterpret_cast<DataGetter>((Scalar* (Derived::*)()) &Derived::data))
    { }

    template<class Derived>
    ResizableRef& operator=(const Eigen::EigenBase<Derived>& other)
    {
        (m->*resizer)(other.rows(), other.cols());
        MatrixType::Map((m->*getData)(), other.rows(), other.cols()) = other;
    }
};

void foo(ResizableRef<Eigen::MatrixXd> A)
{
    A = Eigen::Matrix2d::Identity();
}

int main(int argc, char *argv[])
{
    using namespace Eigen;
    MatrixXd A;
    Matrix<double, Dynamic, Dynamic, Eigen::ColMajor, 20, 12> B;
    Matrix<double, 2, Dynamic, Eigen::ColMajor, 2, 4> C;
    Matrix2d D;
    foo(A);
    foo(B);
    foo(C);
    foo(D);

    std::cout << A << "\n\n" << B << "\n\n" << C << "\n\n" << D << '\n';
}

这可能违反了严格的别名规则,我通常建议重新考虑您的设计。然而,它应该在没有不必要的 运行 时间分配的情况下工作,并且可以安全地防止一些错误的用法:

    MatrixXf fail1;
    Matrix3d fail2;
    foo(fail1); // fails at compile time
    foo(fail2); // fails at runtime