Guest User

Untitled

a guest
Jan 18th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. int heavy_calc() // needed to be called once
  2. {
  3. // sleep(7500000 years)
  4. return 42;
  5. }
  6.  
  7. int main()
  8. {
  9. auto foo = [] {
  10. // And cached for lambda return value
  11. static int cache = heavy_calc();
  12. return cache;
  13. };
  14. return foo() + foo();
  15. }
  16.  
  17. auto foo = [cache=0] () mutable {
  18. // And cached for lambda return value
  19. if(!cache)
  20. cache = heavy_calc();
  21. return cache;
  22. };
  23.  
  24. auto foo = [cache=std::optional<int>{}] () mutable {
  25. // And cached for lambda return value
  26. if(!cache)
  27. cache = heavy_calc();
  28. return *cache;
  29. };
  30.  
  31. int heavy_calc() // needed to be called once
  32. {
  33. // sleep(7500000 years)
  34. return 42;
  35. }
  36.  
  37. int main()
  38. {
  39. auto foo
  40. {
  41. [cache = heavy_calc()](void)
  42. {
  43. return cache;
  44. }
  45. };
  46. return foo() + foo();
  47. }
  48.  
  49. #include <optional>
  50.  
  51. int heavy_calc() // needed to be called once
  52. {
  53. // sleep(7500000 years)
  54. return 42;
  55. }
  56.  
  57.  
  58. int main()
  59. {
  60. struct {
  61. std::optional<int> cache;
  62. int operator()() {
  63. if (!cache) cache = heavy_calc();
  64. return *cache;
  65. }
  66. } foo;
  67. return foo() + foo();
  68. }
Add Comment
Please, Sign In to add comment