Last active
December 19, 2015 14:49
-
-
Save sjolsen/5972469 to your computer and use it in GitHub Desktop.
Simple lazy evaluator for C++
This file contains 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 <functional> | |
#include <optional> | |
template <typename T> | |
class lazy | |
{ | |
std::optional <T> result; | |
std::function <T ()> generator; | |
public: | |
lazy () = default; | |
template <typename Function> | |
lazy (Function&& f) | |
: generator (std::forward <Function> (f)) | |
{ | |
} | |
lazy& operator = (lazy&& other) | |
{ | |
if (other.result == std::nullopt) | |
generator = std::move (other.generator); | |
else | |
result = std::move (other.result); | |
return *this; | |
} | |
lazy& operator = (const lazy& other) | |
{ | |
if (other.result == std::nullopt) | |
generator = other.generator; | |
else | |
result = other.result; | |
return *this; | |
} | |
lazy (const lazy& other) | |
{ | |
*this = other; | |
} | |
lazy (lazy&& other) | |
{ | |
*this = std::move (other); | |
} | |
T operator () () & | |
{ | |
if (result == std::nullopt) | |
result.emplace (generator ()); | |
return *result; | |
} | |
T operator () () && | |
{ | |
if (result == std::nullopt) | |
return generator (); | |
return std::move (*result); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment