2012-12-05 09:40:53 +01:00
|
|
|
/*
|
|
|
|
* Created by Phil on 02/12/2012.
|
|
|
|
* Copyright 2012 Two Blue Cubes Ltd. All rights reserved.
|
|
|
|
*
|
|
|
|
* Distributed under the Boost Software License, Version 1.0. (See accompanying
|
|
|
|
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
|
|
|
*/
|
|
|
|
#ifndef TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED
|
|
|
|
#define TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED
|
|
|
|
|
|
|
|
#include "catch_common.h"
|
|
|
|
|
|
|
|
namespace Catch {
|
|
|
|
|
|
|
|
// An optional type
|
|
|
|
template<typename T>
|
|
|
|
class Option {
|
|
|
|
public:
|
2017-04-25 12:41:30 +02:00
|
|
|
Option() : nullableValue( nullptr ) {}
|
2012-12-05 09:40:53 +01:00
|
|
|
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 )
|
2012-12-05 09:40:53 +01:00
|
|
|
{}
|
2013-07-03 20:14:59 +02:00
|
|
|
|
2012-12-05 09:40:53 +01:00
|
|
|
~Option() {
|
|
|
|
reset();
|
|
|
|
}
|
|
|
|
|
|
|
|
Option& operator= ( Option const& _other ) {
|
2014-03-01 11:38:14 +01:00
|
|
|
if( &_other != this ) {
|
|
|
|
reset();
|
|
|
|
if( _other )
|
|
|
|
nullableValue = new( storage ) T( *_other );
|
|
|
|
}
|
2012-12-05 09:40:53 +01:00
|
|
|
return *this;
|
|
|
|
}
|
2013-07-24 20:13:08 +02:00
|
|
|
Option& operator = ( T const& _value ) {
|
|
|
|
reset();
|
|
|
|
nullableValue = new( storage ) T( _value );
|
|
|
|
return *this;
|
|
|
|
}
|
2012-12-05 09:40:53 +01:00
|
|
|
|
|
|
|
void reset() {
|
|
|
|
if( nullableValue )
|
|
|
|
nullableValue->~T();
|
2017-04-25 12:41:30 +02:00
|
|
|
nullableValue = nullptr;
|
2012-12-05 09:40:53 +01:00
|
|
|
}
|
2013-07-24 20:13:08 +02:00
|
|
|
|
2012-12-05 09:40:53 +01:00
|
|
|
T& operator*() { return *nullableValue; }
|
2013-04-23 19:58:56 +02:00
|
|
|
T const& operator*() const { return *nullableValue; }
|
2012-12-05 09:40:53 +01:00
|
|
|
T* operator->() { return nullableValue; }
|
|
|
|
const T* operator->() const { return nullableValue; }
|
|
|
|
|
2013-06-06 23:54:42 +02: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 20:14:59 +02:00
|
|
|
|
2017-04-25 12:41:30 +02:00
|
|
|
bool operator !() const { return nullableValue == nullptr; }
|
2017-04-25 16:46:48 +02:00
|
|
|
explicit operator bool() const {
|
|
|
|
return some();
|
2012-12-05 09:40:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2017-04-21 08:18:46 +02:00
|
|
|
T *nullableValue;
|
2017-05-08 00:59:44 +02:00
|
|
|
alignas(alignof(T)) char storage[sizeof(T)];
|
2012-12-05 09:40:53 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
} // end namespace Catch
|
|
|
|
|
|
|
|
#endif // TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED
|