Advertisement
EvilingDark

Untitled

May 1st, 2020
732
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. #include "test_runner.h"
  2.  
  3. #include <functional>
  4. #include <memory>
  5. #include <string>
  6. using namespace std;
  7.  
  8. template <typename T>
  9. class LazyValue {
  10. public:
  11.     explicit LazyValue(std::function<T()> init)
  12.         : init_ { init }
  13.     {
  14.     }
  15.  
  16.     bool HasValue() const { return bool(Value); }
  17.     const T& Get() const
  18.     {
  19.         if (Value)
  20.             return *Value.get();
  21.         Value = make_unique<T>(init_());
  22.         return *Value.get();
  23.     }
  24.  
  25. private:
  26.     mutable unique_ptr<T> Value;
  27.     std::function<T()>& init_;
  28. };
  29.  
  30. void UseExample()
  31. {
  32.     const string big_string = "Giant amounts of memory";
  33.  
  34.     LazyValue<string> lazy_string([&big_string] { return big_string; });
  35.  
  36.     ASSERT(!lazy_string.HasValue());
  37.     ASSERT_EQUAL(lazy_string.Get(), big_string);
  38.     ASSERT_EQUAL(lazy_string.Get(), big_string);
  39. }
  40.  
  41. void TestInitializerIsntCalled()
  42. {
  43.     bool called = false;
  44.  
  45.     {
  46.         LazyValue<int> lazy_int([&called] {
  47.             called = true;
  48.             return 0;
  49.         });
  50.     }
  51.     ASSERT(!called);
  52. }
  53.  
  54. int main()
  55. {
  56.     TestRunner tr;
  57.     RUN_TEST(tr, UseExample);
  58.     RUN_TEST(tr, TestInitializerIsntCalled);
  59.     return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement