Optional.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1996-2022 The Squid Software Foundation and contributors
3  *
4  * Squid software is distributed under GPLv2+ license and includes
5  * contributions from numerous individuals and organizations.
6  * Please see the COPYING and CONTRIBUTORS files for details.
7  */
8 
9 #ifndef SQUID__SRC_BASE_OPTIONAL_H
10 #define SQUID__SRC_BASE_OPTIONAL_H
11 
12 #include <exception>
13 #include <type_traits>
14 #include <utility>
15 
17 class BadOptionalAccess: public std::exception
18 {
19 public:
21  /* std::exception API */
22  virtual const char* what() const noexcept override { return "bad-optional-access"; }
23  virtual ~BadOptionalAccess() noexcept = default;
24 };
25 
27 template <typename Value>
29 {
30 public:
31  // std::optional supports non-trivial types as well, but we
32  // do not want to fiddle with unions to disable default Value constructor
33  // until that work becomes necessary
34  static_assert(std::is_trivial<Value>::value, "Value is trivial");
35 
36  constexpr Optional() noexcept {}
37  constexpr explicit Optional(const Value &v): value_(v), hasValue_(true) {}
38 
39  constexpr explicit operator bool() const noexcept { return hasValue_; }
40  constexpr bool has_value() const noexcept { return hasValue_; }
41 
42  const Value &value() const &
43  {
44  if (!hasValue_)
45  throw BadOptionalAccess();
46  return value_;
47  }
48 
49  template <class Other>
50  constexpr Value value_or(Other &&defaultValue) const &
51  {
52  return hasValue_ ? value_ : static_cast<Value>(std::forward<Other>(defaultValue));
53  }
54 
55  template <class Other = Value>
56  Optional &operator =(Other &&otherValue)
57  {
58  value_ = std::forward<Other>(otherValue);
59  hasValue_ = true;
60  return *this;
61  }
62 
63 private:
64  Value value_; // stored value; inaccessible/uninitialized unless hasValue_
65  bool hasValue_ = false;
66 };
67 
68 #endif /* SQUID__SRC_BASE_OPTIONAL_H */
69 
constexpr Optional() noexcept
Definition: Optional.h:36
(limited) std::optional replacement (until we upgrade to C++17)
Definition: Optional.h:29
virtual ~BadOptionalAccess() noexcept=default
pid_t Other()
Definition: Instance.cc:128
#define true
Definition: GnuRegex.c:234
virtual const char * what() const noexcept override
Definition: Optional.h:22
constexpr bool has_value() const noexcept
Definition: Optional.h:40
std::bad_optional_access replacement (until we upgrade to C++17)
Definition: Optional.h:18
constexpr Optional(const Value &v)
Definition: Optional.h:37
constexpr Value value_or(Other &&defaultValue) const &
Definition: Optional.h:50
const Value & value() const &
Definition: Optional.h:42
Value value_
Definition: Optional.h:64
char * class
Definition: smb-errors.c:146

 

Introduction

Documentation

Support

Miscellaneous

Web Site Translations

Mirrors