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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Imla Assuom
  • 189
  • 10
  • 2
    Does this answer your question? [Create N-element constexpr array in C++11](https://stackoverflow.com/questions/19019252/create-n-element-constexpr-array-in-c11) particularly [this answer](https://stackoverflow.com/a/19023500/2757035), which I have made great use of. – underscore_d Jun 11 '20 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 https://gcc.godbolt.org/z/E-M9r5 – Jorge Bellon Jun 11 '20 at 16:27
  • Maybe you would have better luck initializing `array` in the initializer list rather than the constructor body. – Mark Ransom Jun 11 '20 at 16:55
  • 1
    @underscore_d: is what I was looking for, thanks – Imla Assuom Jun 12 '20 at 07:16

1 Answers1

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];
};
max66
  • 65,235
  • 10
  • 71
  • 111