Skip to content

🎨 Preserve enum values in bitset for_each #191

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 12, 2025
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
12 changes: 8 additions & 4 deletions include/stdx/bitset.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -101,13 +101,16 @@ class bitset {
return lhs;
}

using iter_arg_t = conditional_t<std::is_enum_v<decltype(Size)>,
decltype(Size), std::size_t>;

template <typename F> constexpr auto for_each(F &&f) const -> F {
std::size_t i = 0;
for (auto e : storage) {
while (e != 0) {
auto const offset = static_cast<std::size_t>(countr_zero(e));
e &= static_cast<elem_t>(~(bit << offset));
f(i + offset);
f(static_cast<iter_arg_t>(i + offset));
}
i += std::numeric_limits<elem_t>::digits;
}
Expand All @@ -124,7 +127,8 @@ class bitset {
while (e != 0) {
auto const offset = static_cast<std::size_t>(countr_zero(e));
e &= static_cast<elem_t>(~(bit << offset));
init = r(std::move(init), f(i + offset));
init =
r(std::move(init), f(static_cast<iter_arg_t>(i + offset)));
}
i += std::numeric_limits<elem_t>::digits;
}
Expand Down Expand Up @@ -440,8 +444,8 @@ constexpr auto for_each(F &&f, bitset<M, S> const &...bs) -> F {
}

template <typename T, typename F, typename R, auto M, typename... S>
constexpr auto transform_reduce(F &&f, R &&r, T init,
bitset<M, S> const &...bs) -> T {
[[nodiscard]] constexpr auto transform_reduce(F &&f, R &&r, T init,
bitset<M, S> const &...bs) -> T {
if constexpr (sizeof...(bs) == 1) {
return (bs.transform_reduce(std::forward<F>(f), std::forward<R>(r),
std::move(init)),
Expand Down
11 changes: 11 additions & 0 deletions test/bitset.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,17 @@ TEST_CASE("use bitset with enum struct (place_bits construct)", "[bitset]") {
static_assert(bs.to_natural() == 1);
}

TEST_CASE("use bitset with enum struct (for_each)", "[bitset]") {
constexpr auto bs = stdx::bitset<Bits::MAX>{stdx::all_bits};
for_each([](Bits) {}, bs);
}

TEST_CASE("use bitset with enum struct (transform_reduce)", "[bitset]") {
constexpr auto bs = stdx::bitset<Bits::MAX>{stdx::all_bits};
CHECK(transform_reduce([](Bits) { return true; }, std::logical_or{}, false,
bs));
}

#if __cplusplus >= 202002L
TEST_CASE("construct with a ct_string", "[bitset]") {
using namespace stdx::literals;
Expand Down