Debian Codegraph @

Source/Core/Common/Lazy.h

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