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

3

1 Answer 1

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)} {}
Sign up to request clarification or add additional context in comments.

2 Comments

Here is the dupe covering this: stackoverflow.com/a/14495926/12002570
makeArr can be constexpr (without change in C++20, replace fill with for loop pre C++20)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.