能否初始化一个常量Eigen矩阵?

16

我有以下的类:

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成为常量并在构造函数中将其初始化为a到f这些值?如果可以的话,C++11也可以使用,但似乎eigen库不支持初始化列表...


你的意思是这个库:http://eigen.tuxfamily.org吗? - Stefan Weiser
1
没错,就是这样!版本3.2.1。 - Jan Rüegg
2个回答

14

我认为最简单的解决方案是,因为这个类还定义了一个拷贝构造函数

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 <double,5,1,2> :: Matrix(Eigen :: CommaInitializer <Eigen :: Matrix <double,5,1,2> >&)'。 - Jan Rüegg
@JanRüegg 忘记了“完成”的部分,抱歉。 - Marco A.
1
这会复制数据吗?我有印象Eigen还没有完全实现移动。 - Channing Moore

7
您可以编写一个实用函数。
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文件中,会污染全局命名空间吗? - Lucas Myers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接