Search code examples
c++arraysconstants

How to init a constant std::array?


#include <array>
struct A
{
    A(char value, char another);
    const std::array<char, 42> something;  // how to init?
}

Considered approaches:

  • a const_cast is always dangerous and often UB
  • the docs list the only ctor as taking an aggregate parameter - what I want to do is accept some other parameter and initialize the constant
  • removing the constness is ... undesirable. The whole semantics are "create this; it will never need to change"
  • using std::string worries me as inefficient and this is an embedded device
  • std::experimental::make_array looks promising but not standard yet
  • an init list in the ctor seems promising but how?

Can it be done and how?


Solution

  • Use the member initialization list of A's constructor to initialize the array, eg:

    A::A(char value) : arr{value} {}
    

    UPDATE: you edited your question after I posted this answer.

    In your original code, the constructor took a single char, and the array held 1 char, so it was possible to fully initialize the array with that char.

    Now, in your new code, the constructor takes 2 chars, but the array holds 42 chars, so the only way to fully initialize the array with any values other than zeros requires using a helper function that returns a filled array, eg:

    std::array<char, 42> makeArr(char value) {
        std::array<char, 42> temp;
        temp.fill(value);
        return temp;
    }
    
    A::A(char value, char another) : arr{makeArr(value)} {}