So I was answering a question about lazy evaluation (here, my answer is overkill for that case but the idea seems interesting) and it made me think about how lazy evaluation might be done in C++. I came up with a way but I wasn't sure of all the pitfalls in this. Are there other ways of achieving lazy evaluation? how might this be done? What are the pitfalls and this and other designs?
Here is my idea:
#include <iostream>
#include <functional>
#include <memory>
#include <string>
#define LAZY(E) lazy<decltype((E))>{[&](){ return E; }}
template<class T>
class lazy {
private:
typedef std::function<std::shared_ptr<T>()> thunk_type;
mutable std::shared_ptr<thunk_type> thunk_ptr;
public:
lazy(const std::function<T()>& x)
: thunk_ptr(
std::make_shared<thunk_type>([x](){
return std::make_shared<T>(x());
})) {}
const T& operator()() const {
std::shared_ptr<T> val = (*thunk_ptr)();
*thunk_ptr = [val](){ return val; };
return *val;
}
T& operator()() {
std::shared_ptr<T> val = (*thunk_ptr)();
*thunk_ptr = [val](){ return val; };
return *val;
}
};
void log(const lazy<std::string>& msg) {
std::cout << msg() << std::endl;
}
int main() {
std::string hello = "hello";
std::string world = "world";
auto x = LAZY((std::cout << "I was evaluated!\n", hello + ", " + world + "!"));
log(x);
log(x);
log(x);
log(x);
return 0;
}
Some things I was concerned about in my design.
- decltype has some strange rules. Does my usage of decltype have any gotchas? I added extra parentheses around the E in the LAZY macro to make sure that single names got treated fairly, as references just like vec[10] would. Are there other things I'm not accounting for?
- There are lots of layers of indirection in my example. It seems like this might be avoidable.
- Is this correctly memoizing the result so that no matter what or how many things reference the lazy value, it will only evaluate once(this one I'm pretty confident in but lazy evaluation plus tons of shared pointers might be throwing me a loop)
What are your thoughts?
std::future
andstd::async
withstd::launch::deferred
…std::lauch::deferred
actually is lazy evaluated… It gets evaluated on the first thread that tries to access the future.