Search code examples
c++eigen3

How to initialize properly a Eigen::Matrix<std::optional<int>>


I am using a Eigen::Matrix<std::optional<int>> but I don't know how to initialize it.

For numerical types, Matrix::Zero() works nice, but as I'm using std::optional, I would like to initialize to std::nullopt and not to 0.

Is it possible to do so, and if yes, how to do it?


Solution

  • Instead of Matrix::Zero(), use Matrix::Constant(std::nullopt).

    @Nimrod began to answer in a comment:

    Eigen::Matrix<std::optional<int>, 3, 3> matrix;
    matrix.setConstant(std::nullopt);
    

    Then, looking up setConstant, we see there's also a Constant factory function:

    auto matrix = Eigen::Matrix<std::optional<int>, 3, 3>::Constant(std::nullopt);