特征自定义类和函数参数
Eigen custom classes and function parameters
我正在尝试使用 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 特征对象对于将动态矩阵转换为固定矩阵并执行其他强制转换操作非常重要。最后一个问题:在这种情况下使用特征的最佳策略是什么?
至少有三种方法:
-
摆脱
MyVectorType
,通过插件机制使customMethod
成为MatrixBase
的成员。 -
摆脱
MyVectorType
,使customMethod
成为免费功能。 -
通过让
Eigen::Ref<MyVectorType>
继承Ref<MyVectorType::Base>
及其构造函数来专门化,添加一个customMethod
方法并通过调用内部自由函数customMethod_impl
来分解这两个方法。
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 当从函数参数中的临时值调用复制构造函数时
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 如何将lambda作为模板类的成员函数参数
- 模板参数推导失败,函数参数/参数不匹配
- 如何在C++中将迭代器作为函数参数传递
- 将函数参数"const char*"转换为"std::string_view"是
- C++ 如何将数组值解压缩为函数参数
- 主函数参数的属性
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 如何定义在用作函数参数时工作的类模板的转换
- 将函数参数完美转发到函数指针:按值传递呢?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 接受模板作为函数参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- Arduino 函数参数