1

I want to store a calculated const array such that a[i] = i*i -3;

Here is what I was thinking, but I'm not sure:

constexpr int fun(int x) {
  return x * x - 3;
}

template<int N>
struct A {
  constexpr A() : array() {
    for (auto i = 0; i != N; ++i) array[i] = fun(i); 
  }
  int array[N];
};

const A<4> array1{};
const int array2[] = {-3, -2, 1, 6};

I think array1 is initialized, not stored in the executable like array2.

Is it possible to do this without using a macro?

4
  • 2
    Does this answer your question? Create N-element constexpr array in C++11 particularly this answer, which I have made great use of. Commented Jun 11, 2020 at 16:17
  • 1
    Both global variables can be stored in the executable. For an elf binary, for example, they will be located in the .rodata section. What you might experience is the compiler removing the variable because it does not detect any reference to it. If you want to make sure it is visible from the outside regardless of being used or not, declare your variable as extern: see gcc.godbolt.org/z/E-M9r5 Commented Jun 11, 2020 at 16:27
  • Maybe you would have better luck initializing array in the initializer list rather than the constructor body. Commented Jun 11, 2020 at 16:55
  • 1
    @underscore_d: is what I was looking for, thanks Commented Jun 12, 2020 at 7:16

1 Answer 1

1

Is it possible to do this without using a macro?

What about a delegating constructor?

template<int N>
struct A {

  template <int ... Is>
  constexpr A(std::integer_sequence<int, Is...>)
     : array{ fun(Is)... }
   { }

  constexpr A() : A{std::make_integer_sequence<int, N>{}}
   { }

  int array[N];
};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.