-2
#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?

user16217248
  • 3,119
  • 19
  • 19
  • 37
Vorac
  • 8,726
  • 11
  • 58
  • 101
  • Not sure what is wrong with the usual way, using an initialiser list. `A(char value) : a{{value}} {}` – john Apr 05 '23 at 05:29
  • [The object isn't const during construction, or the constructor wouldn't be able to initialize the object](https://stackoverflow.com/a/60556293/12002570) – Jason Apr 05 '23 at 05:29
  • @john this solves it. Sorry for bothering everyone: my brain is non-existent. – Vorac Apr 05 '23 at 05:33

1 Answers1

1

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)} {}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770