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.

91 lines
2.5KB

  1. /*
  2. * Scope value setter, taken from JUCE v4
  3. * Copyright (C) 2013 Raw Material Software Ltd.
  4. * Copyright (c) 2016 ROLI Ltd.
  5. * Copyright (C) 2013-2020 Filipe Coelho <falktx@falktx.com>
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU General Public License as
  9. * published by the Free Software Foundation; either version 2 of
  10. * the License, or any later version.
  11. *
  12. * This program 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. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  18. */
  19. #pragma once
  20. #include "DistrhoUtils.hpp"
  21. START_NAMESPACE_DISTRHO
  22. //=====================================================================================================================
  23. /**
  24. Helper class providing an RAII-based mechanism for temporarily setting and
  25. then re-setting a value.
  26. E.g. @code
  27. int x = 1;
  28. {
  29. ScopedValueSetter setter (x, 2);
  30. // x is now 2
  31. }
  32. // x is now 1 again
  33. {
  34. ScopedValueSetter setter (x, 3, 4);
  35. // x is now 3
  36. }
  37. // x is now 4
  38. @endcode
  39. */
  40. template <typename ValueType>
  41. class ScopedValueSetter
  42. {
  43. public:
  44. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  45. given new value, and will then reset it to its original value when this object is deleted.
  46. Must be used only for 'noexcept' compatible types.
  47. */
  48. ScopedValueSetter(ValueType& valueToSet, ValueType newValue) noexcept
  49. : value(valueToSet),
  50. originalValue(valueToSet)
  51. {
  52. valueToSet = newValue;
  53. }
  54. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  55. given new value, and will then reset it to be valueWhenDeleted when this object is deleted.
  56. */
  57. ScopedValueSetter(ValueType& valueToSet, ValueType newValue, ValueType valueWhenDeleted) noexcept
  58. : value(valueToSet),
  59. originalValue(valueWhenDeleted)
  60. {
  61. valueToSet = newValue;
  62. }
  63. ~ScopedValueSetter() noexcept
  64. {
  65. value = originalValue;
  66. }
  67. private:
  68. //=================================================================================================================
  69. ValueType& value;
  70. const ValueType originalValue;
  71. DISTRHO_DECLARE_NON_COPYABLE(ScopedValueSetter)
  72. DISTRHO_PREVENT_HEAP_ALLOCATION
  73. };
  74. END_NAMESPACE_DISTRHO