Lazy.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright 2017 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include <functional>
  5. #include <utility>
  6. #include <variant>
  7. namespace Common
  8. {
  9. // A Lazy object holds a value. If a Lazy object is constructed using
  10. // a function as an argument, that function will be called to compute
  11. // the value the first time any code tries to access the value.
  12. template <typename T>
  13. class Lazy
  14. {
  15. public:
  16. Lazy() : m_value(T()) {}
  17. Lazy(const std::variant<T, std::function<T()>>& value) : m_value(value) {}
  18. Lazy(std::variant<T, std::function<T()>>&& value) : m_value(std::move(value)) {}
  19. const Lazy<T>& operator=(const std::variant<T, std::function<T()>>& value)
  20. {
  21. m_value = value;
  22. return *this;
  23. }
  24. const Lazy<T>& operator=(std::variant<T, std::function<T()>>&& value)
  25. {
  26. m_value = std::move(value);
  27. return *this;
  28. }
  29. const T& operator*() const { return *ComputeValue(); }
  30. const T* operator->() const { return ComputeValue(); }
  31. T& operator*() { return *ComputeValue(); }
  32. T* operator->() { return ComputeValue(); }
  33. private:
  34. T* ComputeValue() const
  35. {
  36. if (!std::holds_alternative<T>(m_value))
  37. m_value = std::get<std::function<T()>>(m_value)();
  38. return &std::get<T>(m_value);
  39. }
  40. mutable std::variant<T, std::function<T()>> m_value;
  41. };
  42. } // namespace Common