An open API service indexing awesome lists of open source software.

https://github.com/brainstone/cppcompiletimearraygenerator

A tiny header only C++11 (and above) library to generate arrays with a generator function at compile time!
https://github.com/brainstone/cppcompiletimearraygenerator

constexpr cpp cpp11 cpp14 cpp17 cpp20 header-only

Last synced: 3 months ago
JSON representation

A tiny header only C++11 (and above) library to generate arrays with a generator function at compile time!

Awesome Lists containing this project

README

          

# CppCompiletimeArrayGenerator

A tiny header only C++11 (and above) library to generate arrays with a generator function at compile time!

## Motivation

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](https://stackoverflow.com/a/19019432/1996022)! 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!

## Usage

Using this library is really simple. Just include the header and access the array like this:

```cpp
Generator::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 be `constexpr`.

Here's a full example:

```cpp
#include

#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';
}
}
```

## TODO

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