Last active
September 14, 2023 16:04
-
-
Save jemand2001/9da987c9d5c4ca3e7febbe71f1f04fd5 to your computer and use it in GitHub Desktop.
lazy loading of data using initializer and a function to get the actual value
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
| #include <variant> | |
| #include <functional> | |
| #include <iostream> | |
| template <typename Info, typename Actual> | |
| class Lazy { | |
| struct info_holder { | |
| Info x; | |
| }; | |
| using stuff = std::variant<info_holder, Actual>; | |
| stuff value; | |
| std::function<Actual(Info)> producer; | |
| void get_actual() { | |
| if (std::holds_alternative<Actual>(value)) | |
| return; | |
| value = producer(std::get<info_holder>(value).x); | |
| } | |
| public: | |
| template <std::invocable<Info> Producer> | |
| Lazy(Info &&info, Producer &&prod) | |
| : value{std::in_place_type_t<info_holder>{}, std::forward<Info>(info)}, | |
| producer{std::forward<Producer>(prod)} {} | |
| Actual& operator*() { | |
| get_actual(); | |
| return std::get<Actual>(value); | |
| } | |
| Actual* operator->() { | |
| get_actual(); | |
| return &std::get<Actual>(value); | |
| } | |
| }; | |
| template <typename Info, std::invocable<Info> Prod> | |
| Lazy(Info&&, Prod&&) -> Lazy<Info, std::invoke_result_t<Prod, Info>>; | |
| int main() { | |
| Lazy test{1, [](int x) {return x + 1;}}; | |
| std::cout << *test << '\n'; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment