Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

118 lines
2.6KB

  1. /*
  2. * Scope Guard
  3. * Copyright (C) 2017-2018 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. Wrapper(TT&& value, G&& g) noexcept(std::is_nothrow_constructible_v<T, TT>) : m_value(std::forward<TT>(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(Wrapper<T>&& other) noexcept
  43. {
  44. m_value = std::move(other.m_value);
  45. }
  46. void reset(T&& newValue) noexcept(std::is_nothrow_assignable_v<T, decltype(std::move_if_noexcept(newValue))>)
  47. {
  48. m_value = std::forward<T>(newValue);
  49. }
  50. void reset(const T& newValue) noexcept(std::is_nothrow_assignable_v<T, const T&>)
  51. {
  52. m_value = newValue;
  53. }
  54. using type = T;
  55. private:
  56. T m_value;
  57. };
  58. template<class T>
  59. class Wrapper<T&>
  60. {
  61. public:
  62. template<class TT, class G, std::enable_if_t<std::is_convertible_v<TT, T&>, int> = 0>
  63. Wrapper(TT&& value, G&& g) noexcept(std::is_nothrow_constructible_v<TT, T&>) : m_value(static_cast<T&>(value))
  64. {
  65. g.release();
  66. }
  67. T& get() noexcept
  68. {
  69. return m_value.get();
  70. }
  71. const T& get() const noexcept
  72. {
  73. return m_value.get();
  74. }
  75. void reset(Wrapper<T>&& other) noexcept
  76. {
  77. m_value = std::move(other.m_value);
  78. }
  79. void reset(T& newValue) noexcept
  80. {
  81. m_value = std::ref(newValue);
  82. }
  83. using type = std::reference_wrapper<std::remove_reference_t<T>>;
  84. private:
  85. type m_value;
  86. };
  87. }