【问题标题】:Is it possible to initialize a const Eigen matrix?是否可以初始化 const Eigen 矩阵?
【发布时间】:2014-09-29 07:51:28
【问题描述】:

我有以下课程:

class Foo
{
public:
   Foo(double a, double b, double c, double d, double e)
   // This does not work:
   // : m_bar(a, b, c, d, e)
   {
      m_bar << a, b, c, d, e;
   }

private:
   // How can I make this const?
   Eigen::Matrix<double, 5, 1, Eigen::DontAlign> m_bar;
};

如何使 m_bar const 并将其宽度 a 初始化为 f 作为构造函数中的值? C++11 也可以,但是 eigen 似乎不支持初始化列表...

【问题讨论】:

标签: c++ constructor constants eigen initializer-list


【解决方案1】:

自从上课以来我看到的最简单的解决方案也是defines a copy constructor

class Foo
{
public:
   Foo(double a, double b, double c, double d, double e) :
       m_bar( (Eigen::Matrix<double, 5, 1, Eigen::DontAlign>() << a, b, c, d, e).finished() )
   {
   }

private:
   const Eigen::Matrix<double, 5, 1, Eigen::DontAlign> m_bar;
};

【讨论】:

  • 不幸的是,这不起作用。我收到以下错误:没有匹配函数调用 'Eigen::Matrix::Matrix(Eigen::CommaInitializer<:matrix> >& )'
  • @JanRüegg 忘记​​了“完成”部分,抱歉
  • 这会复制数据吗?我的印象是,Eigen 的动作还没有完全实现。
【解决方案2】:

你可以做一个效用函数

Eigen::Matrix<double, 5, 1, Eigen::DontAlign>
make_matrix(double a, double b, double c, double d, double e)
{
    Eigen::Matrix<double, 5, 1, Eigen::DontAlign> m;

    m << a, b, c, d, e;
    return m;
}

然后:

class Foo
{
public:
   Foo(double a, double b, double c, double d, double e) :
       m_bar(make_matrix(a, b, c, d, e))
   {
   }

private:
   const Eigen::Matrix<double, 5, 1, Eigen::DontAlign> m_bar;
};

或者您可以内联该函数并使用finished()

class Foo
{
    using MyMatrice = Eigen::Matrix<double, 5, 1, Eigen::DontAlign>;
public:
   Foo(double a, double b, double c, double d, double e) :
       m_bar((MyMatrice() << a, b, c, d, e).finished())
   {
   }

private:
   const MyMatrice m_bar;
};

【讨论】:

  • 实用函数应该放在哪个文件中?如果放在初始化类的cpp文件中,会不会污染全局命名空间?
猜你喜欢
  • 2022-07-15
  • 1970-01-01
  • 2015-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-24
  • 2018-06-13
相关资源
最近更新 更多