You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

112 line
2.5KB

  1. /*
  2. * Scope Guard
  3. * Copyright (C) 2017 offa
  4. *
  5. * This file is part of Scope Guard.
  6. *
  7. * Scope Guard is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * Scope Guard is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with Scope Guard. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. #pragma once
  21. #include <functional>
  22. #include <type_traits>
  23. namespace sr::detail
  24. {
  25. template<class T>
  26. class Wrapper
  27. {
  28. public:
  29. template<class TT, class G, std::enable_if_t<std::is_constructible_v<T, TT>, int> = 0>
  30. explicit Wrapper(TT&& value, G&& g) noexcept(noexcept(Wrapper{value})) : Wrapper(value)
  31. {
  32. g.release();
  33. }
  34. T& get() noexcept
  35. {
  36. return m_value;
  37. }
  38. const T& get() const noexcept
  39. {
  40. return m_value;
  41. }
  42. void reset(T&& newValue) noexcept(std::is_nothrow_assignable_v<T, decltype(std::move_if_noexcept(newValue))>)
  43. {
  44. m_value = std::move_if_noexcept(newValue);
  45. }
  46. void reset(const T& newValue) noexcept(std::is_nothrow_assignable_v<T, const T&>)
  47. {
  48. m_value = newValue;
  49. }
  50. private:
  51. Wrapper(const T& value) noexcept(noexcept(T{value})) : m_value(value)
  52. {
  53. }
  54. Wrapper(T&& value) noexcept(noexcept(T{std::move_if_noexcept(value)})) : m_value(std::move_if_noexcept(value))
  55. {
  56. }
  57. T m_value;
  58. };
  59. template<class T>
  60. class Wrapper<T&>
  61. {
  62. public:
  63. template<class TT, class G, std::enable_if_t<std::is_convertible_v<TT, T&>, int> = 0>
  64. explicit Wrapper(TT&& value, G&& g) noexcept(noexcept(static_cast<T&>(value))) : m_value(static_cast<T&>(value))
  65. {
  66. g.release();
  67. }
  68. T& get() noexcept
  69. {
  70. return m_value.get();
  71. }
  72. const T& get() const noexcept
  73. {
  74. return m_value.get();
  75. }
  76. void reset(T& newValue) noexcept
  77. {
  78. m_value = std::ref(newValue);
  79. }
  80. private:
  81. std::reference_wrapper<T> m_value;
  82. };
  83. }