Skip to content

Instantly share code, notes, and snippets.

@saxbophone
Last active September 7, 2023 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saxbophone/53ad91dd73a906e63182a8f2fafc9d3a to your computer and use it in GitHub Desktop.
Save saxbophone/53ad91dd73a906e63182a8f2fafc9d3a to your computer and use it in GitHub Desktop.
Unpacking containers with variable-size at compile-time, without needing two duplicate functions to do so.
#include <cstddef>
#include <span>
constexpr std::size_t populate(std::span<int> data) {
std::size_t w = 0;
for (; w < 1000; ++w) {
// this should maybe be a bounds-check instead, but in theory
// this should only be called on containers that are exactly
// the right size...
if (not data.empty()) data[w] = w;
}
return w;
}
#include <array>
#include <functional>
template <std::size_t func(std::span<int>)>
constexpr std::array<int, func({})> unpack() {
std::array<int, func({})> data;
func(data);
return data;
}
constexpr auto CONSTANT = unpack<populate>();
template <int X, int Y>
constexpr std::size_t paramed(std::span<int> data) {
const std::size_t Z = X * Y;
std::size_t c = 0;
for (; c < Z; ++c) {
if (not data.empty()) data[c] = X * Y - c;
}
return c;
}
constexpr auto CLASS_CONSTANT = unpack<paramed<19, 12>>();
int main() {
for (auto c : CONSTANT) {}
for (auto c : CLASS_CONSTANT) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment