Search code examples
c++initializer-liststatic-initialization

C++ static data member initialization error in Eigen


I'm using gcc-10 and Eigen 3.3.9 on Ubuntu 18.04. This snippet compiles and runs fine:

struct S {
  static inline Eigen::Vector3f u{1, 1, 1};
};

int main() {
  Eigen::Vector3f u(1, 1, 1);
}

but the latter version of initialization when applied to static data member, fails to compile:

struct S {
  static inline Eigen::Vector3f u(1, 1, 1);
};

with this error message: error: expected identifier before numeric constant.

Why is that?


Solution

  • As discussed in the paper that added the feature, it was desired that default member initializers support forward lookup for consistency with (constructors’) member initializers. However, member function parameter lists are not such a complete-class context. That leads to ambiguity between function and variable declarations:

    int I() {return -7;}
    struct A {
      int x(I());
      typedef int I;
    };
    

    If A::x is a variable, then lookup for I finds the type A::I, which means that the declaration of x can be interpreted as a function declaration (accepting a function pointer), so it’s a function. If it’s a function, lookup for I doesn’t consider (the subsequent) A::I, so I is ::I and A::x declares a variable initialized to -7. Interchanging ::I and A::I gives two self-consistent interpretations instead of none.

    There’s a rule that a class must not change the meaning of any name lookup performed in its definition, but it’s not clear whether it would apply here since under the variable interpretation the lookup would not change. Instead, the syntactic possibility was simply excluded entirely even though there are of course cases where it would be entirely unambiguous.