C++ eigen static断言将枚举与浮点混淆

Ema*_*ini 1 c++ enums eigen

这是代码:

\n
#include <Eigen/Dense>\nusing namespace Eigen;\nenum { TWO = 2};\nMatrix<float, Dynamic, TWO> m1(42, 2); // good...\nMatrix<float, Dynamic, TWO> m2(42, int(TWO)); // good...\nMatrix<float, Dynamic, TWO> m3(42, TWO); // error!\n
Run Code Online (Sandbox Code Playgroud)\n

当我编译 m3 的声明时,会引发错误,就像枚举值一样TWO是浮点数一样:

\n
$ g++ -I/usr/include/eigen3 -c bug.cpp\nIn file included from /usr/include/eigen3/Eigen/Core:366,\n                 from /usr/include/eigen3/Eigen/Dense:1,\n                 from bug.cpp:1:\n/usr/include/eigen3/Eigen/src/Core/PlainObjectBase.h: In instantiation of \xe2\x80\x98void Eigen::PlainObjectBase<Derived>::_init2(Eigen::Index, Eigen::Index, typename Eigen::internal::enable_if<(typename Eigen::internal::dense_xpr_base<Derived>::type::SizeAtCompileTime != 2), T0>::type*) [with T0 = int; T1 = <unnamed enum>; Derived = Eigen::Matrix<float, -1, 2>; Eigen::Index = long int; typename Eigen::internal::enable_if<(typename Eigen::internal::dense_xpr_base<Derived>::type::SizeAtCompileTime != 2), T0>::type = int]\xe2\x80\x99:\n/usr/include/eigen3/Eigen/src/Core/Matrix.h:302:35:   required from \xe2\x80\x98Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>::Matrix(const T0&, const T1&) [with T0 = int; T1 = <unnamed enum>; _Scalar = float; int _Rows = -1; int _Cols = 2; int _Options = 0; int _MaxRows = -1; int _MaxCols = 2]\xe2\x80\x99\nbug.cpp:6:39:   required from here\n/usr/include/eigen3/Eigen/src/Core/PlainObjectBase.h:740:58: error: static assertion failed: FLOATING_POINT_ARGUMENT_PASSED__INTEGER_WAS_EXPECTED\n  740 |       EIGEN_STATIC_ASSERT(bool(NumTraits<T0>::IsInteger) &&\n      |                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~\n  741 |                           bool(NumTraits<T1>::IsInteger),\n      |                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  \n/usr/include/eigen3/Eigen/src/Core/util/StaticAssert.h:33:54: note: in definition of macro \xe2\x80\x98EIGEN_STATIC_ASSERT\xe2\x80\x99\n   33 |     #define EIGEN_STATIC_ASSERT(X,MSG) static_assert(X,#MSG);\n      |                       \n
Run Code Online (Sandbox Code Playgroud)\n

use*_*522 5

错误消息只是没有选择好,因为它总是提到浮点导致问题,但重点是您需要传递整数类型,而枚举类型则不然。

然而,在 Eigen 版本 3.3.8 中,这一点已经改变,枚举类型现在也被接受,并将转换为其基础整数类型,请参阅导致此提交的问题。由于该版本您的代码可以正常编译,请参阅https://godbolt.org/z/W4jYbKfns