Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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
  24. {
  25. namespace detail
  26. {
  27. template<class T>
  28. class Wrapper
  29. {
  30. public:
  31. template<class TT, class G, std::enable_if_t<std::is_constructible_v<T, TT>, int> = 0>
  32. explicit Wrapper(TT&& value, G&& g) noexcept(noexcept(Wrapper{value})) : Wrapper(value)
  33. {
  34. g.release();
  35. }
  36. T& get() noexcept
  37. {
  38. return m_value;
  39. }
  40. const T& get() const noexcept
  41. {
  42. return m_value;
  43. }
  44. void reset(T&& newValue) noexcept(std::is_nothrow_assignable_v<T, decltype(std::move_if_noexcept(newValue))>)
  45. {
  46. m_value = std::move_if_noexcept(newValue);
  47. }
  48. void reset(const T& newValue) noexcept(std::is_nothrow_assignable_v<T, const T&>)
  49. {
  50. m_value = newValue;
  51. }
  52. private:
  53. Wrapper(const T& value) noexcept(noexcept(T{value})) : m_value(value)
  54. {
  55. }
  56. Wrapper(T&& value) noexcept(noexcept(T{std::move_if_noexcept(value)})) : m_value(std::move_if_noexcept(value))
  57. {
  58. }
  59. T m_value;
  60. };
  61. template<class T>
  62. class Wrapper<T&>
  63. {
  64. public:
  65. template<class TT, class G, std::enable_if_t<std::is_convertible_v<TT, T&>, int> = 0>
  66. explicit Wrapper(TT&& value, G&& g) noexcept(noexcept(static_cast<T&>(value))) : m_value(static_cast<T&>(value))
  67. {
  68. g.release();
  69. }
  70. T& get() noexcept
  71. {
  72. return m_value.get();
  73. }
  74. const T& get() const noexcept
  75. {
  76. return m_value.get();
  77. }
  78. void reset(T& newValue) noexcept
  79. {
  80. m_value = std::ref(newValue);
  81. }
  82. private:
  83. std::reference_wrapper<T> m_value;
  84. };
  85. }
  86. }