Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int heavy_calc() // needed to be called once
- {
- // sleep(7500000 years)
- return 42;
- }
- int main()
- {
- auto foo = [] {
- // And cached for lambda return value
- static int cache = heavy_calc();
- return cache;
- };
- return foo() + foo();
- }
- auto foo = [cache=0] () mutable {
- // And cached for lambda return value
- if(!cache)
- cache = heavy_calc();
- return cache;
- };
- auto foo = [cache=std::optional<int>{}] () mutable {
- // And cached for lambda return value
- if(!cache)
- cache = heavy_calc();
- return *cache;
- };
- int heavy_calc() // needed to be called once
- {
- // sleep(7500000 years)
- return 42;
- }
- int main()
- {
- auto foo
- {
- [cache = heavy_calc()](void)
- {
- return cache;
- }
- };
- return foo() + foo();
- }
- #include <optional>
- int heavy_calc() // needed to be called once
- {
- // sleep(7500000 years)
- return 42;
- }
- int main()
- {
- struct {
- std::optional<int> cache;
- int operator()() {
- if (!cache) cache = heavy_calc();
- return *cache;
- }
- } foo;
- return foo() + foo();
- }
Add Comment
Please, Sign In to add comment