A tiny header only C++11 (and above) library to generate arrays with a generator function at compile time!
Didn't you at some point come across a situation where you had an array that had all its values generated by a function and those values were constant. So
essentially the array will always be initialized to the same values...
Then you thought to yourself: "My generation function is simple enough for it to be constexpr
, so I could just have the compiler generate the array for me at
compile time, couldn't I?" only to be disappointed that there's no good way to do that (up until C++17 anyways)...
That is exactly what happened to me. And I came across a bunch of bad solutions. None really satisfied me until I stumbled across this
gem! While the example given is really simple and just creates an array with increasing numbers (and even makes
the array one element too large) I decided to turn this into a fully fledged compile time array generator!
Using this library is really simple. Just include the header and access the array like this:
Generator<numElements, type, generatorFunction>::value
Notes:
- Sadly you need to specify the
type
. No way to implement this in a way so the compiler can deduct the type. generatorFunction
needs to beconstexpr
.
Here's a full example:
#include <iostream>
#include "Generator.hpp"
constexpr int pow(size_t index) { return index * index; }
int main() {
for (int val : Generator<123, int, pow>::value) {
std::cout << val << '\n';
}
}
Well, while there's not too much left to do here's a list of what I'd like to add over time:
- Doxygen documentation/comments
- Compilable examples