简体   繁体   中英

Brace initialization of Eigen matrix

Using gcc 9.4.0 and Eigen 3.3.7, the following compiles without issue:

#include <Eigen/Dense>

int main(int Argc, char *Argv[]) {
    Eigen::Matrix<int, 1, 4> d = {1, 2, 3, 4};
}

Increasing the length by 1 provokes an error:

#include <Eigen/Dense>

int main(int Argc, char *Argv[]) {
    Eigen::Matrix<int, 1, 5> d = {1, 2, 3, 4, 5};
    }

foo.cpp:6:48: error: could not convert ‘{1, 2, 3, 4, 5}’ from ‘<brace-enclosed initializer list>’ to ‘Eigen::Matrix<int, 1, 5>’
    6 |     Eigen::Matrix<int, 1, 5> d = {1, 2, 3, 4, 5};
      |                                                ^
      |                                                |
      |                                                <brace-enclosed initializer list>

The second case is a copy of a line from the Eigen tutorial page.

Can someone explain the problem with the 2nd case?

UPDATE: Based on comments below, this appears to be a bug in the Eigen library. I've submitted a bug report.

Can someone explain the problem with the 2nd case?

Technically there is nothing wrong with the 2nd case.

This seems to be a eigen library's bug that only happens when you use C++11 with gcc 9.4 and eigen trunk.

The error goes away if you change the standard to C++14 or higher.

See working demo with c++14 with gcc 9.4 and eigen trunk.


On the other hand the problem remains irrespective of the standard c++ version you use with eigen 3.3.7. Demo . I've tried different combinations of standard version with compiler versions and eigen library version and they seem to give inconsistent result. So, this is a bug in the library(eigen) and there is nothing wrong from your side.

Brace initialization is not supported by Eigen 3.3.x. If you write

Eigen::Matrix<int, 1, 4> d = {1, 2, 3, 4};

It will call the Eigen::Matrix(S const& x, S const& y, S const& z, S const& w) constructor link . Eigen has constructors for up to 4 elements, which only work for vector-like matrices which have the correct number of elements at compile-time.

Initializer lists work with Eigen 3.4.x if C++11 or later is enabled: link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM