SaveAndRestore.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===-- SaveAndRestore.h - Utility -------------------------------*- C++ -*-=//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file
  15. /// This file provides utility classes that use RAII to save and restore
  16. /// values.
  17. ///
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_SUPPORT_SAVEANDRESTORE_H
  20. #define LLVM_SUPPORT_SAVEANDRESTORE_H
  21. #include <utility>
  22. namespace llvm {
  23. /// A utility class that uses RAII to save and restore the value of a variable.
  24. template <typename T> struct SaveAndRestore {
  25. SaveAndRestore(T &X) : X(X), OldValue(X) {}
  26. SaveAndRestore(T &X, const T &NewValue) : X(X), OldValue(X) { X = NewValue; }
  27. SaveAndRestore(T &X, T &&NewValue) : X(X), OldValue(std::move(X)) {
  28. X = std::move(NewValue);
  29. }
  30. ~SaveAndRestore() { X = std::move(OldValue); }
  31. const T &get() { return OldValue; }
  32. private:
  33. T &X;
  34. T OldValue;
  35. };
  36. // User-defined CTAD guides.
  37. template <typename T> SaveAndRestore(T &) -> SaveAndRestore<T>;
  38. template <typename T> SaveAndRestore(T &, const T &) -> SaveAndRestore<T>;
  39. template <typename T> SaveAndRestore(T &, T &&) -> SaveAndRestore<T>;
  40. } // namespace llvm
  41. #endif
  42. #ifdef __GNUC__
  43. #pragma GCC diagnostic pop
  44. #endif