選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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