Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions cth/incl/cth/data/cxpr.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#pragma once
#include <algorithm>
#include <array>
#include <cstddef>
#include <ranges>

namespace cth::dt {

/**
* copies the range returned by a constexpr generator into a std::array
* @details allows results computed with constexpr std::vector & co. to outlive constant evaluation
* @tparam Generator callable without arguments that returns a sized range
*/
template<auto Generator>
[[nodiscard]] consteval auto as_cxpr_array() {
using value_type = std::ranges::range_value_t<decltype(Generator())>;
constexpr size_t SIZE = std::ranges::size(Generator());

std::array<value_type, SIZE> result{};
std::ranges::copy(Generator(), result.begin());
return result;
}

}
31 changes: 31 additions & 0 deletions cth/tests/src/data/cxpr_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#include "test.hpp"

#include "cth/data/cxpr.hpp"

#include <string_view>
#include <vector>

namespace cth::dt {

DATA_TEST(as_cxpr_array, main) {
constexpr auto array = as_cxpr_array<[] { return std::vector{1, 2, 3}; }>();

static_assert(array.size() == 3);
EXPECT_EQ(array, (std::array{1, 2, 3}));
}

DATA_TEST(as_cxpr_array, computed_size) {
static constexpr std::string_view CSV = "a,bb,ccc";

constexpr auto splits = as_cxpr_array<[] {
std::vector<size_t> result{};
for(size_t i = 0; i < CSV.size(); i++)
if(CSV[i] == ',')
result.push_back(i);
return result;
}>();

EXPECT_EQ(splits, (std::array<size_t, 2>{1, 4}));
}

}
Loading