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?

3

1 Answer 1

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!

Not the answer you're looking for? Browse other questions tagged or ask your own question.