Skip to content

Instantly share code, notes, and snippets.

@DrkWithT
Created April 3, 2025 18:33
Show Gist options
  • Save DrkWithT/e38825012880d6ef8bba7d8c74af4ada to your computer and use it in GitHub Desktop.
Save DrkWithT/e38825012880d6ef8bba7d8c74af4ada to your computer and use it in GitHub Desktop.
#include <array>
#include <type_traits>
#include <print>
/// Compiled on g++ with: -std=c++23 -Og
/// Util. types
enum class StepPolicy {
forth,
back
};
template <bool Flag, typename T1, typename T2>
struct chooser_t {
using type = T2;
};
template <typename T1, typename T2>
struct chooser_t <true, T1, T2> {
using type = T1;
};
template <bool Flag, typename T1, typename T2>
using chosen_of_t = chooser_t<Flag, T1, T2>::type;
/// meh number ranging utility
template <StepPolicy Sp, typename T>
class GenStep {};
template <typename T>
class GenStep <StepPolicy::forth, T> {
private:
T m_current;
T m_step;
public:
constexpr GenStep() noexcept (std::is_trivially_constructible_v<T>)
: m_current {}, m_step {} {}
explicit constexpr GenStep(T current, T step) noexcept (std::is_trivially_copyable_v<T>)
: m_current {current}, m_step {step} {}
[[nodiscard]] constexpr T operator()() noexcept {
auto temp = m_current;
m_current += m_step;
return temp;
}
};
template <typename T>
class GenStep <StepPolicy::back, T> {
private:
T m_current;
T m_step;
public:
constexpr GenStep() noexcept (std::is_trivially_constructible_v<T>)
: m_current {}, m_step {} {}
explicit constexpr GenStep(T current, T step) noexcept (std::is_trivially_copyable_v<T>)
: m_current {current}, m_step {step} {}
[[nodiscard]] constexpr T operator()() noexcept {
auto temp = m_current;
m_current -= m_step;
return temp;
}
};
template <std::size_t Count, template <StepPolicy, typename> typename Generator, StepPolicy P, typename Item>
auto make_range_items(Generator<P, Item>& gen) noexcept (std::is_trivially_copyable_v<Item>) -> chosen_of_t<(Count > 1), std::array<Item, Count>, Item> {
if constexpr (Count == 0) {
return Item {};
} else if constexpr (Count == 1) {
return gen();
} else {
std::array<Item, Count> foo;
for (auto i = 0UL; i < Count; i++) {
foo[i] = gen();
}
return foo;
}
}
int main() {
GenStep<StepPolicy::forth, int> counter {0, 1};
auto counted_4 = make_range_items<4>(counter);
for (const auto& num : counted_4) {
std::print("{}\n", num);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment