optional.hpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*************************************************************************
  2. *
  3. * Copyright 2016 Realm Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. **************************************************************************/
  18. #pragma once
  19. #ifndef REALM_UTIL_OPTIONAL_HPP
  20. #define REALM_UTIL_OPTIONAL_HPP
  21. #include <optional>
  22. #include <ostream>
  23. namespace realm {
  24. namespace util {
  25. template <class T>
  26. using Optional = std::optional<T>;
  27. using None = std::nullopt_t;
  28. template <class T, class... Args>
  29. Optional<T> some(Args&&... args)
  30. {
  31. return std::make_optional<T>(std::forward<Args>(args)...);
  32. }
  33. using std::make_optional;
  34. constexpr auto none = std::nullopt;
  35. template <class T>
  36. struct RemoveOptional {
  37. using type = T;
  38. };
  39. template <class T>
  40. struct RemoveOptional<Optional<T>> {
  41. using type = typename RemoveOptional<T>::type; // Remove recursively
  42. };
  43. /**
  44. * Writes a T to an ostream, with special handling if T is a std::optional.
  45. *
  46. * This function supports both optional and non-optional Ts, so that callers don't need to do their own dispatch.
  47. */
  48. template <class T>
  49. std::ostream& stream_possible_optional(std::ostream& os, const T& rhs)
  50. {
  51. return os << rhs;
  52. }
  53. template <class T>
  54. std::ostream& stream_possible_optional(std::ostream& os, const std::optional<T>& rhs)
  55. {
  56. if (rhs) {
  57. os << "some(" << *rhs << ")";
  58. }
  59. else {
  60. os << "none";
  61. }
  62. return os;
  63. }
  64. } // namespace util
  65. using util::none;
  66. } // namespace realm
  67. #endif // REALM_UTIL_OPTIONAL_HPP