Boost logo

Boost :

Subject: [boost] utility class: lazy data type
From: Zachary Turner (divisortheory_at_[hidden])
Date: 2009-01-18 17:07:15


I wrote this class to support lazy evaluation and caching of values. It
seems like it would be useful for inclusion as a miscellaneous class in
boost. It seems like this pattern occurs pretty often in practice, it's
even the fundamental implementation method for singletons, and at least I
often have tons of boost::optionals in my code, with get accessors on the
classes that check if there's a value, if not call a fetch function, and
then return the value. It's cleaner to just call get every single time and
not worry about it. I don't consider myself a guru, so suggestions on how
to make it better are, of course, appreciated.

template<class T>
class lazy
{
public:
    explicit lazy(function<T ()> fetch)
        : _fetch(fetch)
    {
    }

    T get()
    {
        if (!_cached)
            _cached = _fetch();
        return _cached.get();
    }

private:
    optional<T> _cached;
    function<T ()> _fetch;
};

Perhaps such a class is too trivial to be included, but here it is
nonetheless.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk