Skip to content

Instantly share code, notes, and snippets.

@sjolsen
Last active December 19, 2015 14:49
Show Gist options
  • Save sjolsen/5972469 to your computer and use it in GitHub Desktop.
Save sjolsen/5972469 to your computer and use it in GitHub Desktop.
Simple lazy evaluator for C++
#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