Option.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. // Option represents a pointer with explicit null semantics. Use sites are
  6. // required to deal with the null possibility.
  7. //----------------------------------------------------------------------------
  8. #pragma once
  9. namespace regex
  10. {
  11. template<class T>
  12. class Option
  13. {
  14. const T * value;
  15. public:
  16. // Info: Construct an empty option of type T
  17. Option()
  18. : value(nullptr)
  19. { }
  20. // Info: Create an empty or non-empty option of type T
  21. // Parameters: value - the pointer to hold. May be null.
  22. Option(const T * value)
  23. : value(value)
  24. { }
  25. // Info: Get the held value if there is one. Assert otherwise.
  26. const T * GetValue() const
  27. {
  28. Assert(HasValue());
  29. return value;
  30. }
  31. // Info: Returns true if there is value.
  32. bool HasValue() const
  33. {
  34. return value!=nullptr;
  35. }
  36. // Info: Get the held value if there is one, otherwise call the given function
  37. // to produce a value
  38. // Parameters: f - function which produces a value of type T
  39. template<class F>
  40. const T * GetValueOrDefault(F f) const
  41. {
  42. if(value==nullptr)
  43. {
  44. return f();
  45. }
  46. return value;
  47. }
  48. // Info: Get the held value if there is one, otherwise return the given default value
  49. // Parameters: defaultValue - function which produces a value of type T
  50. const T* GetValueOrDefaultValue(const T * defaultValue) const
  51. {
  52. if(value==nullptr)
  53. {
  54. return defaultValue;
  55. }
  56. return value;
  57. }
  58. // Info: Get the held value if there is one, otherwise return nullptr
  59. const T* GetValueOrNull() const
  60. {
  61. return value;
  62. }
  63. };
  64. }