2 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * @file optional_value.h
18 * @author Lukasz Wrzosek (l.wrzosek@samsung.com)
22 #ifndef DPL_OPTIONAL_H
23 #define DPL_OPTIONAL_H
25 #include <dpl/exception.h>
28 template <typename Type>
34 DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
35 DECLARE_EXCEPTION_TYPE(Base, NullReference)
44 Optional(const Type& t) :
57 Throw(typename Exception::NullReference);
62 const Type& operator*() const
65 Throw(typename Exception::NullReference);
70 const Type* operator->() const
73 Throw(typename Exception::NullReference);
81 Throw(typename Exception::NullReference);
86 bool operator!() const
91 Optional<Type>& operator=(const Type& other)
98 bool operator==(const Optional<Type>& aSecond) const
100 return LogicalOperator<true>(*this, aSecond,
101 std::equal_to<Type>(), std::equal_to<bool>());
104 bool operator==(const Type& aSecond) const
106 return Optional<Type>(aSecond) == *this;
109 bool operator!=(const Optional<Type>& aSecond) const
111 return !(*this == aSecond);
114 bool operator<(const Optional<Type>& aSecond) const
116 return LogicalOperator<false>(*this, aSecond,
117 std::less<Type>(), std::less<bool>());
120 bool operator>(const Optional<Type>& aSecond) const
122 return LogicalOperator<false>(*this, aSecond,
123 std::greater<Type>(), std::greater<bool>());
126 bool operator<=(const Optional<Type>& aSecond) const
128 return *this == aSecond || *this < aSecond;
131 bool operator>=(const Optional<Type>& aSecond) const
133 return *this == aSecond || *this > aSecond;
136 static Optional<Type> Null;
142 template <bool taEquality, typename taComparator, typename taNullComparator>
143 static bool LogicalOperator(const Optional<Type>& aFirst,
144 const Optional<Type>& aSecond,
145 taComparator aComparator,
146 taNullComparator aNullComparator)
148 if (aFirst.m_null == aSecond.m_null) {
152 return aComparator(aFirst.m_value, aSecond.m_value);
155 return aNullComparator(aFirst.m_null, aSecond.m_null);
160 template<typename Type>
161 Optional<Type> Optional<Type>::Null = Optional<Type>();
164 template<typename Type>
165 std::ostream& operator<<(std::ostream& aStream,
166 const DPL::Optional<Type>& aOptional)
168 if (aOptional.IsNull()) {
169 return aStream << "null optional";
171 return aStream << *aOptional;
175 #endif // DPL_OPTIONAL_VALUE_H