特征自定义类和函数参数

Eigen custom classes and function parameters

本文关键字:函数 参数 自定义 特征      更新时间:2023-10-16

我正在尝试使用 Eigen 替换代码中当前使用的矩阵库。我有几个像这样的类,将自定义方法添加到基矩阵类。在这个例子中,我用 Eigen 替换了父类:

#include <iostream>
#include <eigen3/Eigen/Dense>
class MyVectorType: public Eigen::Matrix<double, 3, 1> {
public:
    MyVectorType(void) :
            Eigen::Matrix<double, 3, 1>() {
    }
    typedef Eigen::Matrix<double, 3, 1> Base;
    // This constructor allows you to construct MyVectorType from Eigen expressions
    template<typename OtherDerived>
    MyVectorType(const Eigen::MatrixBase<OtherDerived>& other) :
            Eigen::Matrix<double, 3, 1>(other) {
    }
    // This method allows you to assign Eigen expressions to MyVectorType
    template<typename OtherDerived>
    MyVectorType & operator=(const Eigen::MatrixBase<OtherDerived>& other) {
        this->Base::operator=(other);
        return *this;
    }
    void customMethod() {
        //bla bla....
    }
};

最大的问题是在方法中管理自定义类并不容易。例:

void foo(MyVectorType& a) {
    ....
    a.customMethod();
}
void foo(Eigen::Ref<MyVectorType::Base> a) {
    ....
    a.customMethod(); <---can't call customMethod here
}
Eigen::Matrix<double, -1, -1, 0, 15, 15> m(3,1);
foo(m); <---can't call it with m;
Eigen::Map<Matrix<double, 3, 1> > map(m.data(), 3, 1);
Eigen::Ref<Matrix<double, 3, 1> > ref(map);
foo(ref); <---it works but I can't call custom method
通常 Eigen

提供 Ref 模板类,但我不能将其与自定义类一起使用,因为如果我使用 Ref,我将无法在此示例中在 foo 中调用 customMethod,我应该在我的示例中使用 Eigen::Ref。避免使用 Ref 是一个大问题,因为使用 Map 和 Ref 特征对象对于将动态矩阵转换为固定矩阵并执行其他强制转换操作非常重要。最后一个问题:在这种情况下使用特征的最佳策略是什么?

至少有三种方法:

  1. 摆脱MyVectorType,通过插件机制使customMethod成为MatrixBase的成员。

  2. 摆脱MyVectorType,使customMethod成为免费功能。

  3. 通过让Eigen::Ref<MyVectorType>继承Ref<MyVectorType::Base>及其构造函数来专门化,添加一个customMethod方法并通过调用内部自由函数customMethod_impl来分解这两个方法。