Skip to content

Instantly share code, notes, and snippets.

@martinus
Created October 25, 2020 12:09
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 martinus/f912813cffa337c7860f0b1dbd935196 to your computer and use it in GitHub Desktop.
Save martinus/f912813cffa337c7860f0b1dbd935196 to your computer and use it in GitHub Desktop.
class UpToExecutor {
public:
UpToExecutor(int64_t begin, int64_t end, int64_t step)
: mBegin(begin)
, mEnd(end)
, mStep(step) {}
template <typename Op>
void operator()(Op op) {
auto end = ((mEnd - mBegin) / mStep) * mStep + mBegin;
for (int64_t x = mBegin; x != end; x += mStep) {
if constexpr (std::is_invocable_v<Op, uint64_t>) {
op(x);
} else {
op();
}
}
}
private:
int64_t mBegin{};
int64_t mEnd{};
int64_t mStep{};
};
class UpTo {
public:
explicit UpTo(int64_t begin, int64_t step)
: mBegin(begin)
, mStep(step) {}
auto operator()(int64_t endInclusive) const -> UpToExecutor {
return UpToExecutor(mBegin, endInclusive + mStep, mStep);
}
private:
int64_t mBegin{};
int64_t mStep{};
};
auto operator""_upto(unsigned long long t) -> UpTo {
return UpTo(t, 1);
}
auto operator""_downto(unsigned long long t) -> UpTo {
return UpTo(t, -1);
}
auto operator""_times(unsigned long long t) -> UpToExecutor {
return UpToExecutor(0, t, 1);
}
TEST_CASE("ArithmeticsTest") {
10_times([](int x) {
fmt::print("hello {}\n", x);
});
5_times([] {
fmt::print("goodbye\n");
});
8_upto(10)([](uint64_t x) {
fmt::print("it is {}\n", x);
});
5_downto(-2)([](int64_t x) {
fmt::print("11_downto(5): {}\n", x);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment