Files
Catch2/src/catch2/internal/catch_optional.hpp
T

99 lines
2.7 KiB
C++
Raw Normal View History

// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
2021-10-05 20:11:42 +02:00
#ifndef CATCH_OPTIONAL_HPP_INCLUDED
#define CATCH_OPTIONAL_HPP_INCLUDED
namespace Catch {
// An optional type
template<typename T>
2021-10-05 20:11:42 +02:00
class Optional {
public:
2021-10-05 20:11:42 +02:00
Optional() : nullableValue( nullptr ) {}
Optional( T const& _value )
: nullableValue( new( storage ) T( _value ) )
{}
2021-10-05 20:11:42 +02:00
Optional( Optional const& _other )
2017-04-25 12:41:30 +02:00
: nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
{}
2013-07-03 19:14:59 +01:00
2021-10-05 20:11:42 +02:00
~Optional() {
reset();
}
2021-10-05 20:11:42 +02:00
Optional& operator= ( Optional const& _other ) {
2014-03-01 10:38:14 +00:00
if( &_other != this ) {
reset();
if( _other )
nullableValue = new( storage ) T( *_other );
}
return *this;
}
2021-10-05 20:11:42 +02:00
Optional& operator = ( T const& _value ) {
2013-07-24 19:13:08 +01:00
reset();
nullableValue = new( storage ) T( _value );
return *this;
}
void reset() {
if( nullableValue )
nullableValue->~T();
2017-04-25 12:41:30 +02:00
nullableValue = nullptr;
}
2013-07-24 19:13:08 +01:00
T& operator*() {
assert(nullableValue);
return *nullableValue;
}
T const& operator*() const {
assert(nullableValue);
return *nullableValue;
}
T* operator->() {
assert(nullableValue);
return nullableValue;
}
const T* operator->() const {
assert(nullableValue);
return nullableValue;
}
2013-06-06 22:54:42 +01:00
T valueOr( T const& defaultValue ) const {
return nullableValue ? *nullableValue : defaultValue;
}
2017-04-25 12:41:30 +02:00
bool some() const { return nullableValue != nullptr; }
bool none() const { return nullableValue == nullptr; }
2013-07-03 19:14:59 +01:00
2017-04-25 12:41:30 +02:00
bool operator !() const { return nullableValue == nullptr; }
2017-04-25 14:46:48 +00:00
explicit operator bool() const {
return some();
}
2021-03-08 14:43:42 +01:00
friend bool operator==(Optional const& a, Optional const& b) {
if (a.none() && b.none()) {
return true;
} else if (a.some() && b.some()) {
return *a == *b;
} else {
return false;
}
}
friend bool operator!=(Optional const& a, Optional const& b) {
return !( a == b );
}
private:
T *nullableValue;
2017-05-08 00:59:44 +02:00
alignas(alignof(T)) char storage[sizeof(T)];
};
} // end namespace Catch
2021-10-05 20:11:42 +02:00
#endif // CATCH_OPTIONAL_HPP_INCLUDED