Optional.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
  2. #ifndef C10_UTIL_OPTIONAL_H_
  3. #define C10_UTIL_OPTIONAL_H_
  4. #include <optional>
  5. #include <type_traits>
  6. // Macros.h is not needed, but it does namespace shenanigans that lots
  7. // of downstream code seems to rely on. Feel free to remove it and fix
  8. // up builds.
  9. namespace c10 {
  10. #if !defined(FBCODE_CAFFE2) && !defined(C10_NODEPRECATED)
  11. // NOLINTNEXTLINE(misc-unused-using-decls)
  12. using std::bad_optional_access;
  13. // NOLINTNEXTLINE(misc-unused-using-decls)
  14. using std::make_optional;
  15. // NOLINTNEXTLINE(misc-unused-using-decls)
  16. using std::nullopt;
  17. // NOLINTNEXTLINE(misc-unused-using-decls)
  18. using std::nullopt_t;
  19. // NOLINTNEXTLINE(misc-unused-using-decls)
  20. using std::optional;
  21. #endif
  22. #if !defined(FBCODE_CAFFE2) && !defined(C10_NODEPRECATED)
  23. namespace detail_ {
  24. // the call to convert<A>(b) has return type A and converts b to type A iff b
  25. // decltype(b) is implicitly convertible to A
  26. template <class U>
  27. constexpr U convert(U v) {
  28. return v;
  29. }
  30. } // namespace detail_
  31. template <class T, class F>
  32. [[deprecated(
  33. "Please use std::optional::value_or instead of c10::value_or_else")]] constexpr T
  34. value_or_else(const std::optional<T>& v, F&& func) {
  35. static_assert(
  36. std::is_convertible_v<typename std::invoke_result_t<F>, T>,
  37. "func parameters must be a callable that returns a type convertible to the value stored in the optional");
  38. return v.has_value() ? *v : detail_::convert<T>(std::forward<F>(func)());
  39. }
  40. template <class T, class F>
  41. [[deprecated(
  42. "Please use std::optional::value_or instead of c10::value_or_else")]] constexpr T
  43. value_or_else(std::optional<T>&& v, F&& func) {
  44. static_assert(
  45. std::is_convertible_v<typename std::invoke_result_t<F>, T>,
  46. "func parameters must be a callable that returns a type convertible to the value stored in the optional");
  47. return v.has_value() ? constexpr_move(std::move(v).contained_val())
  48. : detail_::convert<T>(std::forward<F>(func)());
  49. }
  50. #endif
  51. } // namespace c10
  52. #endif // C10_UTIL_OPTIONAL_H_
  53. #else
  54. #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
  55. #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)