Optional.h 1.9 KB

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