7

这是我的示例代码:

(请注意被 包围的部分#if ENABLE_MY_COMPILE_ERROR

#include <Eigen/Core>
#include <iostream>

#define ENABLE_MY_COMPILE_ERROR 1

void f1(const Eigen::Ref<Eigen::MatrixXd> a, 
        const Eigen::Ref<Eigen::MatrixXd> b, 
        Eigen::Ref<Eigen::MatrixXd> c)
{
   c = a * b;
}

int main(int argc, const char *argv[])
{
   Eigen::Matrix3d M;
   Eigen::Vector3d x;
   Eigen::Vector3d y;

   M.setRandom();
   x.setRandom();

   std::cout<<"M = \n"<<M<<std::endl;
   std::cout<<"x = \n"<<x<<std::endl;
   std::cout<<"M * x = \n"<<M * x<<std::endl;

   {
      y.setZero();
      f1(M,x,y);

      std::cout<<"y = \n"<<y<<std::endl;
   }

   {
      Eigen::Matrix3d& MRef = M;

      y.setZero();
      f1(MRef,x,y);

      std::cout<<"y = \n"<<y<<std::endl;
   }

#if ENABLE_MY_COMPILE_ERROR
   {
      const Eigen::Matrix3d& MRef = M;

      y.setZero();
      f1(MRef,x,y);

      std::cout<<"y = \n"<<y<<std::endl;
   }
#endif
}

这是我得到的编译错误ENABLE_MY_COMPILE_ERROR != 0

In file included from ../../../../external/src/eigen-current/Eigen/Core:334:0,
                 from Eigen_Ref.C:1:
../../../../external/src/eigen-current/Eigen/src/Core/PlainObjectBase.h: In constructor ‘Eigen::Ref<PlainObjectType, Options, StrideType>::Ref(const Eigen::DenseBase<OtherDerived>&, typename Eigen::internal::enable_if<(bool)((Eigen::internal::is_lvalue<Derived>::value && (bool)(typename Eigen::internal::traits<Eigen::Ref<_PlainObjectType, _Options, _StrideType> >::match<Derived>::MatchAtCompileTime))), Derived>::type*, int) [with Derived = Eigen::Matrix<double, 3, 3>; PlainObjectType = Eigen::Matrix<double, -1, -1>; int Options = 0; StrideType = Eigen::OuterStride<>; typename Eigen::internal::enable_if<(bool)((Eigen::internal::is_lvalue<Derived>::value && (bool)(typename Eigen::internal::traits<Eigen::Ref<_PlainObjectType, _Options, _StrideType> >::match<Derived>::MatchAtCompileTime))), Derived>::type = Eigen::Matrix<double, 3, 3>]’:
../../../../external/src/eigen-current/Eigen/src/Core/PlainObjectBase.h:726:12: error: ‘Eigen::PlainObjectBase<Eigen::Matrix<double, 3, 3> >::<anonymous enum> Eigen::PlainObjectBase<Eigen::Matrix<double, 3, 3> >::ThisConstantIsPrivateInPlainObjectBase’ is private
Eigen_Ref.C:47:18: error: within this context

因此,显然以下内容是不兼容的:

  • const Eigen::Ref<Eigen::MatrixXd> a

  • const Eigen::Matrix3d& MRef = M

我的问题是:

  • 这是设计使然,还是 Eigen::Ref<> 的错误/缺点?

  • 如果按照设计,那么在保持 const 正确性的同时干净地传递 Matrix 对象的好方法是什么?

例如,如果有一个带有成员函数的类:

const Matrix3d& SomeClass::getTheSuperDuperMatrix() const 
{
   return this->superDuperMat;
}

我计划在一段代码中多次使用这个函数的返回值,我想用一个短名称创建一个对它的引用,我希望它是一个常量引用。

const Matrix3d& M = someClassInstance.getTheSuperDuperMatrix();

但是,如果我将 M 传递给接受参数的函数,我将得到上述编译错误const Ref<Matrix3d>,例如:

f1(M,x,y);

仅供参考,我目前正在使用以下版本的 Eigen:

Version: 3.2.91
Revision 5696:af94f93db432
4

1 回答 1

7

这是因为const Eigen::Ref<Eigen::MatrixXd>不是 const 引用。它必须像这样声明:

Eigen::Ref<const Eigen::MatrixXd>
于 2013-12-11T08:24:24.590 回答