Created
November 23, 2024 07:52
-
-
Save jonwis/1d3d333e7d775b37528891f24daebcde to your computer and use it in GitHub Desktop.
Lazy C++ type suggestion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://godbolt.org/z/xnd359j99 | |
#include <optional> | |
#include <mutex> | |
#include <functional> | |
template<typename T> struct default_lazy_init { | |
T operator()() const { | |
return T{}; | |
} | |
}; | |
template<typename T, typename TDispenser = default_lazy_init<T>> struct lazy_init : TDispenser | |
{ | |
lazy_init() = default; | |
template<typename Q> lazy_init(Q&& td) : TDispenser(std::move(td)) { } | |
auto operator->() { | |
return std::addressof(get()); | |
} | |
T& get() { | |
ensure_ready(); | |
return m_store.value(); | |
} | |
auto operator->() const { | |
return std::addressof(get()); | |
} | |
T const& get() const { | |
return m_store.value(); | |
} | |
private: | |
void ensure_ready() { | |
std::call_once(m_flag, [&] { | |
auto dispenser = static_cast<TDispenser*>(this); | |
m_store = (*dispenser)(); | |
}); | |
} | |
mutable std::once_flag m_flag; | |
std::optional<T> m_store; | |
}; | |
lazy_init<std::vector<uint8_t>> buffer; | |
lazy_init<std::wstring, std::function<std::wstring()>> temp([]{return L"kittens";}); | |
std::wstring boop() { | |
buffer->insert(buffer->end(), 32); | |
return temp.get(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not super clear the mutable is required on line 44