Skip to content

Commit

Permalink
extend OptRef to simplify the using of to<Type> methods (#28)
Browse files Browse the repository at this point in the history
* extend OptRef to simplify the using of to<Type> methods

Signed-off-by: wangbaiping <[email protected]>
  • Loading branch information
code committed Aug 7, 2023
1 parent b6dedde commit 6192674
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions hessian2/object.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,32 @@ constexpr const char* UntypedListMagicString = "untypedlist";
constexpr const char* NullMagicString = "null";

template <class T>
using OptConstRef = absl::optional<std::reference_wrapper<const T>>;
class OptRef : public absl::optional<std::reference_wrapper<T>> {
public:
// Inherit absl::optional's constructors.
using absl::optional<std::reference_wrapper<T>>::optional;

// Rewrite operator-> then we can use the OptRef as a pointer and not need
// to use the value().get() to get the inner object. Please ensure that the
// OptRef has_value() will return true before using operator->.
T* operator->() { return &(this->value().get()); }
const T* operator->() const { return &(this->value().get()); }

// To get the pointer of the inner object. If the OptRef has_value() return
// false then this method will return nullptr.
T* ptr() { return this->has_value() ? &(this->value().get()) : nullptr; }
const T* ptr() const {
return this->has_value() ? &(this->value().get()) : nullptr;
}

// To get the reference of the inner object. Please ensure that the OptRef
// has_value() will return true before using these methods.
T& ref() { return this->value().get(); }
const T& ref() const { return this->value().get(); }
};

template <class T>
using OptRef = absl::optional<std::reference_wrapper<T>>;
using OptConstRef = OptRef<const T>;

using Binary = std::vector<uint8_t>;

Expand Down

0 comments on commit 6192674

Please sign in to comment.