1

I'm trying to initialize the member vec within the class scope, but the compiler throws a more cryptic error.

class A {
public:
    static const size_t sz = 10;
    static const std::vector<double> vec{ sz }; // error
};

The compiler (gcc) gives the following error(s):

error: in-class initialization of static data member 'std::vector<double> A::vec' of non-literal type
   10 |     static std::vector<double> vec{ sz };
      |                                ^~~
error: non-constant in-class initialization invalid for non-inline static member 'A::vec'
   10 |     static std::vector<double> vec{ sz };
      |                                        ^
note: (an out of class initialization is required)

How I can fix this?

mada
  • 1,646
  • 1
  • 15
  • Notice the message saying "non-constant in-class initialization invalid for **non-inline** static member..." (emphasis mine)? That's a hint about how to solve your problem. – Some programmer dude Sep 24 '22 at 08:30
  • 1
    With that said, why do you want a *constant* vector? You can't modify the contents of it. Even assignment like `vec[0] = 5.0` is invalid. – Some programmer dude Sep 24 '22 at 08:31
  • Dupe: [Initialize a static const non-integral data member of a class](https://stackoverflow.com/questions/8490451/initialize-a-static-const-non-integral-data-member-of-a-class). Another dupe: [Why are only static const integral types & enums allowed In-class Initialization?](https://stackoverflow.com/questions/9656941/why-cant-i-initialize-non-const-static-member-or-static-array-in-class) – Jason Sep 24 '22 at 08:38

1 Answers1

1

Ordinarily, static data members may not be initialized in the class body. However, we can provide in-class initializers for static members that are only of const-qualified integral type. If non-integral static members are used, and you need to provide an in-class initializer, the data member shall be constexpr literal type. In any case, the initializers must be constant expressions. If the type of the member is not literal type (hence constexpr can't be used), the static member shall not have a default member initializer, instead, it can be defined outside the class.

So your error is just because std::vector<double> is of non-integral type. Also, you can't declare vec as constexpr because std::vector<double> is not a literal type.

So to fix your above example, you can do this:

class A {
public:
    static const size_t sz = 10;
    static const std::vector<double> vec;
};

const std::vector<double> A::vec{ sz };

(Demo)

As pointed out in the commnets, note that, making vec const-qualified, you will lose some of the vector features. For example, you can't modify any element after adding it!

mada
  • 1,646
  • 1
  • 15