Skip to content

Instantly share code, notes, and snippets.

@aryan-gupta
Last active January 5, 2018 00:11
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 aryan-gupta/17547b51c51104f20e3402780f6b72da to your computer and use it in GitHub Desktop.
Save aryan-gupta/17547b51c51104f20e3402780f6b72da to your computer and use it in GitHub Desktop.
Python ranged based for loop using C++17
#include <array>
#include <iostream>
// This function is th heart of the range loop. Returns
// an array that is allocated on the stack. Because this
// is a constexpr, this array of incrementing numbers is
// calculated at compile time. Please note that if negative
// numbers needs to be used, change \tparam T to a signed
// integer
/// @tparam The size of the array (number of iterations)
/// @tparam The type of int used to iterate
/// @param The start number (defaults to 0)
/// @param The step size (defaults to 1)
/// @return Statically created array. Contains the numbers to iterate over
template <size_t N, typename T = unsigned>
constexpr std::array<T, N> range(T b = 0, T s = 1) {
std::array<T, N> ret{};
for (auto& i : ret) {
i = b;
b += s;
}
return ret;
}
/// The practical way to use this
void practical_way() {
for (auto a : range<5>())
std::cout << a << " ";
std::cout << std::endl;
}
#define range(N) range<N>()
// https://stackoverflow.com/questions/11761703/overloading-macro-on-number-of-arguments
// #define range(B, E) range<(E) - (B)>(B)
//#define range(B, E, S) range<((E) - (B) / (S))>((B), (S))
#define for(x) for(auto x)
#define in :
// The over-the-top way to do it
// see macro's above
void impractical_way() {
for(a in range(5))
std::cout << a << " ";
std::cout << std::endl;
}
int main() {
practical_way();
impractical_way();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment