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_r407463134
 
 

 ##########
 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 {
 
 Review comment:
   It depends on whether we take the default or non-default path. If we take 
the default pass, passing by value is better than pass by argument. Perhaps we 
can add an overload to both cases later

----------------------------------------------------------------
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

Reply via email to