Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

109 rindas
2.7KB

  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. namespace sr
  23. {
  24. namespace detail
  25. {
  26. template<class T>
  27. struct Wrapper
  28. {
  29. template<class TT, class G, std::enable_if_t<std::is_constructible<T, TT>::value, 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<T, decltype(std::move_if_noexcept(newValue))>::value)
  43. {
  44. m_value = std::move_if_noexcept(newValue);
  45. }
  46. void reset(const T& newValue) noexcept(std::is_nothrow_assignable<T, const T&>::value)
  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. struct Wrapper<T&>
  61. {
  62. template<class TT, class G, std::enable_if_t<std::is_convertible<TT, T&>::value, int> = 0>
  63. explicit Wrapper(TT&& value, G&& g) noexcept(noexcept(static_cast<T&>(value))) : 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(T& newValue) noexcept
  76. {
  77. m_value = std::ref(newValue);
  78. }
  79. private:
  80. std::reference_wrapper<T> m_value;
  81. };
  82. }
  83. }