tqchen commented on a change in pull request #5314: [RUNTIME][IR] Allow
non-nullable ObjectRef, introduce Optional<T>.
URL: https://github.com/apache/incubator-tvm/pull/5314#discussion_r407462403
##########
File path: include/tvm/runtime/container.h
##########
@@ -610,7 +611,146 @@ struct PackedFuncValueConverter<::tvm::runtime::String> {
}
};
+/*!
+ * \brief Optional container that to represent to a Nullable variant of T.
+ * \tparam T The original ObjectRef.
+ *
+ * \code
+ *
+ * Optional<String> opt0 = nullptr;
+ * Optional<String> opt1 = String("xyz");
+ * CHECK(opt0 == nullptr);
+ * CHECK(opt1 == "xyz");
+ *
+ * \endcode
+ */
+template<typename T>
+class Optional : public ObjectRef {
+ public:
+ using ContainerType = typename T::ContainerType;
+ static_assert(std::is_base_of<ObjectRef, T>::value,
+ "Optional is only defined for ObjectRef.");
+ // default constructors.
+ Optional() = default;
+ Optional(const Optional<T>&) = default;
+ Optional(Optional<T>&&) = default;
+ Optional<T>& operator=(const Optional<T>&) = default;
+ Optional<T>& operator=(Optional<T>&&) = default;
+ /*!
+ * \brief Construct from an ObjectPtr
+ * whose type already matches the ContainerType.
+ * \param ptr
+ */
+ explicit Optional(ObjectPtr<Object> ptr) : ObjectRef(ptr) {}
+ // nullptr handling.
+ // disallow implicit conversion as 0 can be implicitly converted to nullptr_t
+ explicit Optional(std::nullptr_t) {}
+ Optional<T>& operator=(std::nullptr_t) {
+ data_ = nullptr;
+ return *this;
+ }
+ // normal value handling.
+ Optional(T other) // NOLINT(*)
+ : ObjectRef(std::move(other)) {
+ }
+ Optional<T>& operator=(T other) {
+ ObjectRef::operator=(std::move(other));
+ return *this;
+ }
+ // delete the int constructor
+ // since Optional<Integer>(0) is ambiguious
+ // 0 can be implicitly casted to nullptr_t
+ explicit Optional(int val) = delete;
+ Optional<T>& operator=(int val) = delete;
+ /*!
+ * \return A not-null container value in the optional.
+ * \note This function performs not-null checking.
+ */
+ T value() const {
+ CHECK(data_ != nullptr);
+ return T(data_);
+ }
+ /*!
+ * \return The contained value if the Optional is not null
+ * otherwise return the default_value.
+ */
+ T value_or(T default_value) const {
+ return data_ != nullptr ? T(data_) : default_value;
+ }
+ /*! \return Whether the container is not nullptr.*/
+ explicit operator bool() const {
Review comment:
This overload is needed to enable sugar
```c++
if (auto opt = GetSomeOptional) {
// code
}
```
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]
With regards,
Apache Git Services