Possible to initialize const std::array with repeated function call?

Viewed 1095

Is it possible to do this

int foo(){
  static int i=0;
  ret = i++;
  return ret;
}
const std::array<int,3> arr = {{foo(),foo(),foo()}};

in a (template?) function or a way that specifies "call foo for the initialization of every member"?i.e.

const std::array<int,3> arr = fill_with_foo<3,foo>();

For context,arr is a buffer from a queue from which N elements will be read (known at compile time). Currently I am using code generation to create the long form, and I have a function which simply allocates a normal array, fills it with a for loop and returns the array, but I wonder if it is possible to have the buffer array const.

//Edit: unlike in the linked "duplicate", I need

int foo();

to be nondeterministic at compile time, i.e. I think constexpr is out of the question (as I said, it needs to read from a queue which is filled at runtime). I am mainly interested in eliding useless copies

2 Answers
Related