ForEach.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
  2. #pragma once
  3. #ifndef NV_CORE_FOREACH_H
  4. #define NV_CORE_FOREACH_H
  5. /*
  6. These foreach macros are very non-standard and somewhat confusing, but I like them.
  7. */
  8. #include "nvcore.h"
  9. #if NV_CC_CPP11
  10. #define NV_FOREACH(i, container) \
  11. for (auto i = (container).start(); !(container).isDone(i); (container).advance(i))
  12. #elif NV_CC_GNUC // If typeof is available:
  13. /*
  14. Ideally we would like to write this:
  15. #define NV_FOREACH(i, container) \
  16. for(decltype(container)::PseudoIndex i((container).start()); !(container).isDone(i); (container).advance(i))
  17. But gcc versions prior to 4.7 required an intermediate type. See:
  18. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=6709
  19. */
  20. #define NV_FOREACH(i, container) \
  21. typedef typeof(container) NV_STRING_JOIN2(cont,__LINE__); \
  22. for(NV_STRING_JOIN2(cont,__LINE__)::PseudoIndex i((container).start()); !(container).isDone(i); (container).advance(i))
  23. #else // If typeof not available:
  24. #define NV_NEED_PSEUDOINDEX_WRAPPER 1
  25. #include <new> // placement new
  26. struct PseudoIndexWrapper {
  27. template <typename T>
  28. PseudoIndexWrapper(const T & container) {
  29. nvStaticCheck(sizeof(typename T::PseudoIndex) <= sizeof(memory));
  30. new (memory) typename T::PseudoIndex(container.start());
  31. }
  32. // PseudoIndex cannot have a dtor!
  33. template <typename T> typename T::PseudoIndex & operator()(const T * /*container*/) {
  34. return *reinterpret_cast<typename T::PseudoIndex *>(memory);
  35. }
  36. template <typename T> const typename T::PseudoIndex & operator()(const T * /*container*/) const {
  37. return *reinterpret_cast<const typename T::PseudoIndex *>(memory);
  38. }
  39. uint8 memory[4]; // Increase the size if we have bigger enumerators.
  40. };
  41. #define NV_FOREACH(i, container) \
  42. for(PseudoIndexWrapper i(container); !(container).isDone(i(&(container))); (container).advance(i(&(container))))
  43. #endif
  44. // Declare foreach keyword.
  45. #if !defined NV_NO_USE_KEYWORDS
  46. # define foreach NV_FOREACH
  47. # define foreach_index NV_FOREACH
  48. #endif
  49. #endif // NV_CORE_FOREACH_H