static_switch.h 1.2 KB

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