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>
30 template <typename Type>
36 DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
37 DECLARE_EXCEPTION_TYPE(Base, NullReference)
47 Optional(const Type& t) :
60 if (m_null) Throw(typename Exception::NullReference);
64 const Type& operator*() const
66 if (m_null) Throw(typename Exception::NullReference);
70 const Type* operator->() const
72 if (m_null) Throw(typename Exception::NullReference);
78 if (m_null) Throw(typename Exception::NullReference);
82 bool operator!() const
87 Optional<Type>& operator=(const Type& other)
94 bool operator==(const Optional<Type>& aSecond) const
96 return LogicalOperator<true>(*this, aSecond, std::equal_to<Type>(), std::equal_to<bool>());
99 bool operator==(const Type& aSecond) const
101 return Optional<Type>(aSecond) == *this;
104 bool operator!=(const Optional<Type>& aSecond) const
106 return !(*this == aSecond);
109 bool operator<(const Optional<Type>& aSecond) const
111 return LogicalOperator<false>(*this, aSecond, std::less<Type>(), std::less<bool>());
114 bool operator>(const Optional<Type>& aSecond) const
116 return LogicalOperator<false>(*this, aSecond, std::greater<Type>(), std::greater<bool>());
119 bool operator<=(const Optional<Type>& aSecond) const
121 return *this == aSecond || *this < aSecond;
124 bool operator>=(const Optional<Type>& aSecond) const
126 return *this == aSecond || *this > aSecond;
129 static Optional<Type> Null;
135 template <bool taEquality, typename taComparator, typename taNullComparator>
136 static bool LogicalOperator(const Optional<Type>& aFirst, const Optional<Type>& aSecond,
137 taComparator aComparator, taNullComparator aNullComparator)
139 if (aFirst.m_null == aSecond.m_null)
147 return aComparator(aFirst.m_value, aSecond.m_value);
152 return aNullComparator(aFirst.m_null, aSecond.m_null);
157 template<typename Type>
158 Optional<Type> Optional<Type>::Null = Optional<Type>();
162 template<typename Type>
163 std::ostream& operator<<(std::ostream& aStream, const DPL::Optional<Type>& aOptional)
165 if (aOptional.IsNull())
167 return aStream << "null optional";
171 return aStream << *aOptional;
175 #endif // DPL_OPTIONAL_VALUE_H