Search code examples
c++type-conversioneigentensor

Is this declaration of an Eigen::Tensor in C++ safe, or buggy? And should I submit an issue for it?


Using Eigen's unsupported Tensor module, if I do:

    size_t dim0 = 3;
    size_t dim1 = 2;
    size_t dim2 = 4;
    Eigen::Tensor<double, 3> var(dim0, dim1, dim2);

I get the following error:

/usr/local/include/eigen3/unsupported/Eigen/CXX11/src/Tensor/TensorDimensions.h:287:167: error: non-constant-expression cannot be narrowed from type 'unsigned long' to 'std::__1::array<long, 3>::value_type' (aka 'long') in initializer list [-Wc++11-narrowing]

But the code compiles OK if I explicitly cast the dimensions to long int:

    long int dim0 = 3;
    long int dim1 = 2;
    long int dim2 = 4;
    Eigen::Tensor<double, 3> var(dim0, dim1, dim2);

Questions:

  1. For what size variable will this become unsafe? If at all?
  2. Surely Eigen should be generally accepting a (size_t) type as a dimension argument? Should I file a bug report for this or is it intended behaviour here?

I'm using C++11, clang on Mac OSX (haven't tested other platforms).


Solution

  • The narrowing warning will appear for any type that cannot be converted to a long without loss. So that means size_t, but also long long on some platforms.

    In general, loop indices should be signed, hence Eigen decision to store long for sizes.

    For more info on this, there are some cppcon topics (Chandler Carruth, mainly) about undefined behavior that help the compiler.