1 /* 2 * Copyright (C) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef LIBTEXTCLASSIFIER_UTILS_OPTIONAL_H_ 18 #define LIBTEXTCLASSIFIER_UTILS_OPTIONAL_H_ 19 20 #include "utils/base/logging.h" 21 22 namespace libtextclassifier3 { 23 24 // Holds an optional value. 25 template <class T> 26 class Optional { 27 public: Optional()28 Optional() : init_(false) {} 29 Optional(const Optional & other)30 Optional(const Optional& other) { 31 init_ = other.init_; 32 if (other.init_) { 33 value_ = other.value_; 34 } 35 } 36 Optional(T value)37 explicit Optional(T value) : init_(true), value_(value) {} 38 39 Optional& operator=(Optional&& other) { 40 init_ = other.init_; 41 if (other.init_) { 42 value_ = std::move(other); 43 } 44 return *this; 45 } 46 47 Optional& operator=(T&& other) { 48 init_ = true; 49 value_ = std::move(other); 50 return *this; 51 } 52 has_value()53 constexpr bool has_value() const { return init_; } 54 55 T const* operator->() const { 56 TC3_CHECK(init_) << "Bad optional access."; 57 return value_; 58 } 59 value()60 T const& value() const& { 61 TC3_CHECK(init_) << "Bad optional access."; 62 return value_; 63 } 64 value_or(T && default_value)65 T const& value_or(T&& default_value) const& { 66 return (init_ ? value_ : default_value); 67 } 68 set(const T & value)69 void set(const T& value) { 70 init_ = true; 71 value_ = value; 72 } 73 74 private: 75 bool init_; 76 T value_; 77 }; 78 79 } // namespace libtextclassifier3 80 81 #endif // LIBTEXTCLASSIFIER_UTILS_OPTIONAL_H_ 82