c++ - Eigen 自定义类和函数参数
问题描述
我正在尝试使用 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 Eigen 对象对于将动态矩阵转换为固定矩阵并执行其他转换操作非常重要。最后一个问题:在这种情况下使用 Eigen 的最佳策略是什么?
解决方案
至少有以下三种方法:
通过插件机制摆脱
MyVectorType
并成为customMethod
成员。MatrixBase
摆脱
MyVectorType
并做customMethod
一个免费的功能。Eigen::Ref<MyVectorType>
通过让它继承Ref<MyVectorType::Base>
及其构造函数,添加一个customMethod
方法并通过调用内部自由函数分解这两个方法来进行特殊化customMethod_impl
。
推荐阅读
- ocaml - OCaml 中的多态函数不接受不同的类型
- python - (Adafruit_Python_DHT - Raspberry Pi) 在 get_platform RuntimeError: Unknown platform
- algorithm - 重叠不止一次的间隔的最大长度子集
- java - 用 Java 打印 SQL 查询 (JTextPane)
- c# - 如何从 CSharpScript 评估中捕获控制台输出
- javascript - 用户代理无法在新更新的网络浏览器上运行
- ios - 当服务器没有返回数据时,使用组合处理成功响应
- java - 我可以在不解析的情况下比较对象和字符串吗
- javascript - 使用 Enzyme 测试在不同组件中呈现的导入组件
- colors - PyGtk3:获取当前条目文本颜色