catch_option.hpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Created by Phil on 02/12/2012.
  3. * Copyright 2012 Two Blue Cubes Ltd. All rights reserved.
  4. *
  5. * Distributed under the Boost Software License, Version 1.0. (See accompanying
  6. * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. */
  8. #ifndef TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED
  9. #define TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED
  10. namespace Catch {
  11. // An optional type
  12. template<typename T>
  13. class Option {
  14. public:
  15. Option() : nullableValue( nullptr ) {}
  16. Option( T const& _value )
  17. : nullableValue( new( storage ) T( _value ) )
  18. {}
  19. Option( Option const& _other )
  20. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  21. {}
  22. ~Option() {
  23. reset();
  24. }
  25. Option& operator= ( Option const& _other ) {
  26. if( &_other != this ) {
  27. reset();
  28. if( _other )
  29. nullableValue = new( storage ) T( *_other );
  30. }
  31. return *this;
  32. }
  33. Option& operator = ( T const& _value ) {
  34. reset();
  35. nullableValue = new( storage ) T( _value );
  36. return *this;
  37. }
  38. void reset() {
  39. if( nullableValue )
  40. nullableValue->~T();
  41. nullableValue = nullptr;
  42. }
  43. T& operator*() { return *nullableValue; }
  44. T const& operator*() const { return *nullableValue; }
  45. T* operator->() { return nullableValue; }
  46. const T* operator->() const { return nullableValue; }
  47. T valueOr( T const& defaultValue ) const {
  48. return nullableValue ? *nullableValue : defaultValue;
  49. }
  50. bool some() const { return nullableValue != nullptr; }
  51. bool none() const { return nullableValue == nullptr; }
  52. bool operator !() const { return nullableValue == nullptr; }
  53. explicit operator bool() const {
  54. return some();
  55. }
  56. private:
  57. T *nullableValue;
  58. alignas(alignof(T)) char storage[sizeof(T)];
  59. };
  60. } // end namespace Catch
  61. #endif // TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED