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

85 lines
2.3 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
#ifndef CATCH_OPTION_HPP_INCLUDED
#define CATCH_OPTION_HPP_INCLUDED
namespace Catch {
// An optional type
template<typename T>
class Option {
public:
2017-04-25 12:41:30 +02:00
Option() : nullableValue( nullptr ) {}
Option( T const& _value )
: nullableValue( new( storage ) T( _value ) )
{}
Option( Option 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
~Option() {
reset();
}
Option& operator= ( Option const& _other ) {
2014-03-01 10:38:14 +00:00
if( &_other != this ) {
reset();
if( _other )
nullableValue = new( storage ) T( *_other );
}
return *this;
}
2013-07-24 19:13:08 +01:00
Option& operator = ( T const& _value ) {
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();
}
private:
T *nullableValue;
2017-05-08 00:59:44 +02:00
alignas(alignof(T)) char storage[sizeof(T)];
};
} // end namespace Catch
#endif // CATCH_OPTION_HPP_INCLUDED