0

I want to have a pre filled array (or vector) that should be part of the executable, that is being calculated at compile time. For example. I want a templated array or vector that can be filled with 0 to size with a counter value.

I am targeting c++17

I have tried to solve this by myself and so far no results. Here is my code:

#include <cstdio>
#include <array>

// I need an array or vector that contains 0x00 to 0xFF
// If the type is unsigned short, then should be 0x0000 to 0xFFFF
static constexpr std::array<unsigned char, 256> buffer = {0x00};

template <typename T, std::size_t N>
constexpr void fillArray(std::array<T, N> theArray) {
    T counter = 0; // Fill the array
    for(int i = 0; i < N; ++i) {
        theArray[i] = counter++;
    }
}

int main(int argc, char** argv) {

    fillArray(buffer); // This needs to be compile time

    for(int i = 0; i < buffer.size(); ++i) {
        printf("%d\n", buffer[i]);
    }

    return 0;
}

The for loop prints only 0s

DEKKER
  • 877
  • 6
  • 19
  • It works for me: https://wandbox.org/permlink/gNB9QLUybY8V8Lvd – Marek R Aug 10 '22 at 09:45
  • 1
    You cannot "fill" a constant variable. [This answers your problem](https://stackoverflow.com/a/63098631/7691729). – Quimby Aug 10 '22 at 09:47
  • Extending `Quimby` point: you doing that wrong. When function is `constexpr` it doesn't mean it may modyfy `constexpr` symbols all over the place. It means it can be used to initialize `constexpr` value. Regular function can't be used to initialize `constexpr` value. See example I've provided. – Marek R Aug 10 '22 at 10:18

0 Answers0