1 // 2 // Copyright 2015 The ANGLE Project Authors. All rights reserved. 3 // Use of this source code is governed by a BSD-style license that can be 4 // found in the LICENSE file. 5 // 6 // Optional.h: 7 // Represents a type that may be invalid, similar to std::optional. 8 // 9 10 #ifndef COMMON_OPTIONAL_H_ 11 #define COMMON_OPTIONAL_H_ 12 13 #include <utility> 14 15 template <class T> 16 struct Optional 17 { OptionalOptional18 Optional() : mValid(false), mValue(T()) {} 19 OptionalOptional20 Optional(const T &valueIn) : mValid(true), mValue(valueIn) {} 21 OptionalOptional22 Optional(const Optional &other) : mValid(other.mValid), mValue(other.mValue) {} 23 24 Optional &operator=(const Optional &other) 25 { 26 this->mValid = other.mValid; 27 this->mValue = other.mValue; 28 return *this; 29 } 30 31 Optional &operator=(const T &value) 32 { 33 mValue = value; 34 mValid = true; 35 return *this; 36 } 37 38 Optional &operator=(T &&value) 39 { 40 mValue = std::move(value); 41 mValid = true; 42 return *this; 43 } 44 resetOptional45 void reset() { mValid = false; } 46 InvalidOptional47 static Optional Invalid() { return Optional(); } 48 validOptional49 bool valid() const { return mValid; } valueOptional50 const T &value() const { return mValue; } 51 52 bool operator==(const Optional &other) const 53 { 54 return ((mValid == other.mValid) && (!mValid || (mValue == other.mValue))); 55 } 56 57 bool operator!=(const Optional &other) const { return !(*this == other); } 58 59 bool operator==(const T &value) const { return mValid && (mValue == value); } 60 61 bool operator!=(const T &value) const { return !(*this == value); } 62 63 private: 64 bool mValid; 65 T mValue; 66 }; 67 68 #endif // COMMON_OPTIONAL_H_ 69