foreach.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // This code is in the public domain -- Ignacio Castaño <[email protected]>
  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_GNUC // If typeof or decltype is available:
  10. #if !NV_CC_CPP11
  11. # define NV_DECLTYPE typeof // Using a non-standard extension over typeof that behaves as C++11 decltype
  12. #else
  13. # define NV_DECLTYPE decltype
  14. #endif
  15. /*
  16. Ideally we would like to write this:
  17. #define NV_FOREACH(i, container) \
  18. for(NV_DECLTYPE(container)::PseudoIndex i((container).start()); !(container).isDone(i); (container).advance(i))
  19. But gcc versions prior to 4.7 required an intermediate type. See:
  20. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=6709
  21. */
  22. #define NV_FOREACH(i, container) \
  23. typedef NV_DECLTYPE(container) NV_STRING_JOIN2(cont,__LINE__); \
  24. for(NV_STRING_JOIN2(cont,__LINE__)::PseudoIndex i((container).start()); !(container).isDone(i); (container).advance(i))
  25. #else // If typeof not available:
  26. #include <new> // placement new
  27. struct PseudoIndexWrapper {
  28. template <typename T>
  29. PseudoIndexWrapper(const T & container) {
  30. nvStaticCheck(sizeof(typename T::PseudoIndex) <= sizeof(memory));
  31. new (memory) typename T::PseudoIndex(container.start());
  32. }
  33. // PseudoIndex cannot have a dtor!
  34. template <typename T> typename T::PseudoIndex & operator()(const T * /*container*/) {
  35. return *reinterpret_cast<typename T::PseudoIndex *>(memory);
  36. }
  37. template <typename T> const typename T::PseudoIndex & operator()(const T * /*container*/) const {
  38. return *reinterpret_cast<const typename T::PseudoIndex *>(memory);
  39. }
  40. uint8 memory[4]; // Increase the size if we have bigger enumerators.
  41. };
  42. #define NV_FOREACH(i, container) \
  43. for(PseudoIndexWrapper i(container); !(container).isDone(i(&(container))); (container).advance(i(&(container))))
  44. #endif
  45. // Declare foreach keyword.
  46. #if !defined NV_NO_USE_KEYWORDS
  47. # define foreach NV_FOREACH
  48. # define foreach_index NV_FOREACH
  49. #endif
  50. #endif // NV_CORE_FOREACH_H