static_switch.h 946 B

1234567891011121314151617181920212223242526
  1. // Inspired by
  2. // https://github.com/NVIDIA/DALI/blob/main/include/dali/core/static_switch.h
  3. // and https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/Dispatch.h
  4. #pragma once
  5. /// @param COND - a boolean expression to switch by
  6. /// @param CONST_NAME - a name given for the constexpr bool variable.
  7. /// @param ... - code to execute for true and false
  8. ///
  9. /// Usage:
  10. /// ```
  11. /// BOOL_SWITCH(flag, BoolConst, [&] {
  12. /// some_function<BoolConst>(...);
  13. /// });
  14. /// ```
  15. #define BOOL_SWITCH(COND, CONST_NAME, ...) \
  16. [&] { \
  17. if (COND) { \
  18. static constexpr bool CONST_NAME = true; \
  19. return __VA_ARGS__(); \
  20. } else { \
  21. static constexpr bool CONST_NAME = false; \
  22. return __VA_ARGS__(); \
  23. } \
  24. }()