Created
November 6, 2014 19:39
-
-
Save gchudnov/155ec120ac0cf9366ce1 to your computer and use it in GitHub Desktop.
Lazy (call once)
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 <iostream> | |
#include <memory> | |
#include <functional> | |
#include <mutex> | |
template <typename T> | |
struct lazy { | |
public: | |
template <typename Fun> | |
explicit lazy(Fun&& fun) : fun(std::forward<Fun>(fun)) {} | |
T& get() const { | |
std::call_once(flag, [this] { ptr.reset(fun()); }); | |
return *ptr; | |
} | |
private: | |
std::once_flag flag; | |
std::unique_ptr<T> ptr; | |
std::function<T*()> fun; | |
}; | |
class foo {}; | |
int main() { | |
lazy<foo> x([] { return new foo; }); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment