c++ - 以多个 Eigen 对象作为参数的函数的最佳实践

标签 c++ parameters eigen

我发现以 Eigen 对象为参数的函数设计很麻烦。而 Eigen Documentation 中的信息很有帮助,它暗示了模板参数的笨拙方法。假设,我们要编写一个几何例程,如线平面交点。一个简单而透明的方法是:

template<typename _Tp> 
bool planeLineIntersect(const Eigen::Matrix<_Tp, 3, 1>& planePoint, 
                        const Eigen::Matrix<_Tp, 3, 1>& planeNormal, 
                        const Eigen::Matrix<_Tp, 3, 1>& linePoint, 
                        const Eigen::Matrix<_Tp, 3, 1>& lineDir,
                        Eigen::Matrix<_Tp, 3, 1>& intersectionPoint)

这看起来比较令人愉快,看到它的人可以了解到每个参数都应该是同一类型的 3D vector 。然而,直接地,这不允许任何类型的 Eigen 表达式(我们必须为我们使用的每个表达式调用 Eigen::Matrix 构造函数)。因此,如果表达式与此一起使用,我们需要创建不必要的临时对象。

建议的解决方案是:

template<typename Derived1, typename Derived2, typename Derived3, typename Derived4, typename Derived5> 
bool planeLineIntersect(const Eigen::MatrixBase<Derived1>& planePoint, 
                        const Eigen::MatrixBase<Derived2>& planeNormal, 
                        const Eigen::MatrixBase<Derived3>& linePoint, 
                        const Eigen::MatrixBase<Derived4>& lineDir,
                        const Eigen::MatrixBase<Derived5>& intersectionPoint)

这不会透露任何有关预期矩阵的信息,也不会透露哪些参数用于输入和输出,因为我们必须对 intersectionPoint 进行常量转换以允许输出参数中的表达式。据我了解,这是允许在所有函数参数中使用 Eigen 表达式的唯一方法。尽管支持不雅的表达方式,但第一个片段对我来说仍然更讨人喜欢。

我的问题:

  1. 您认为第二个代码片段是该示例的最佳解决方案吗?
  2. 您是否曾对输出参数使用 const-cast 解决方案,或者您认为失去透明度不值得?
  3. 您使用哪些准则/最佳实践来编写 Eigen 函数?

最佳答案

对于这么小的固定大小的对象,我不会费心去使用第一种解决方案。

输出函数参数很少是一个好的方法。在您的特定情况下,一种方法是创建一个 PlaneLineIntersection 类,其构造函数采用平面和直线,存储交集的结果,然后提供访问器来查询计算结果(没有交集,它是一个点,一行)。

顺便说一句,您是否注意到 Eigen/Geometry 模块的 HyperPlane 和 ParametrizedLine 类? ParametrizedLine 类有一个带有 HyperPlane 的 intersectionPoint 成员(尽管它是有限的,因为它假定交点确实存在并且它是一个点)。

关于c++ - 以多个 Eigen 对象作为参数的函数的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18447789/

相关文章:

c++ - 使用 Eigen 3 库编写一个以转置作为参数的函数

c++ - Eigen SparseLU 解决 error read access violation,this->m_sup_to_col was 0x111011101110112

c++ - 混淆 L 值和 R 值括号

javascript - 如何在 WT 中保存 Ace 编辑器中的所有文本?

c++ - 在 C++ 中从 cin 按下 ESC 按钮之前如何读取

ruby-on-rails - Ruby on Rails - 将值传递给 link_to

c++ - Effective placement of lock_guard - 来自 Effective Modern C++ 的第 16 条

Java可变函数参数

c++ - 如何确定 MSADO 命令参数的大小

c++ - 使用 Eigen 库的 mingw 出现未知错误