optional.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. *
  3. * Copyright 2019 gRPC authors.
  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. #ifndef GRPC_CORE_LIB_GPRPP_OPTIONAL_H
  19. #define GRPC_CORE_LIB_GPRPP_OPTIONAL_H
  20. #include <grpc/support/port_platform.h>
  21. #if GRPC_USE_ABSL
  22. #include "absl/types/optional.h"
  23. namespace grpc_core {
  24. template <typename T>
  25. using Optional = absl::optional<T>;
  26. } // namespace grpc_core
  27. #else
  28. #include <utility>
  29. namespace grpc_core {
  30. /* A make-shift alternative for absl::Optional. This can be removed in favor of
  31. * that once absl dependencies can be introduced. */
  32. template <typename T>
  33. class Optional {
  34. public:
  35. Optional() : value_() {}
  36. template <typename... Args>
  37. T& emplace(Args&&... args) {
  38. value_ = T(std::forward<Args>(args)...);
  39. set_ = true;
  40. return value_;
  41. }
  42. bool has_value() const { return set_; }
  43. void reset() { set_ = false; }
  44. T value() const { return value_; }
  45. private:
  46. T value_;
  47. bool set_ = false;
  48. };
  49. } /* namespace grpc_core */
  50. #endif
  51. #endif /* GRPC_CORE_LIB_GPRPP_OPTIONAL_H */