16

I have the following class:

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;
};

How Can I make m_bar const and initialize it width a to f as values in the constructor? C++11 would also be fine, but initializer lists don't seem to be supported by eigen...

Jan Rüegg
  • 9,587
  • 8
  • 63
  • 105

2 Answers2

14

Simplest solution I see since the class also 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;
};
Marco A.
  • 43,032
  • 26
  • 132
  • 246
7

You may do a utility function

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;
}

And then:

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;
};

Or you can inline that function and using 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;
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • In what file should you put the utility function? If you put it in the cpp file where the class is initialized, would it pollute the global namespace? – Lucas Myers Jun 11 '21 at 16:37