Advertisement
kutuzzzov

Урок 6 Логическая константность

May 23rd, 2023
787
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. #include <cassert>
  2. #include <functional>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. template <typename T>
  8. class LazyValue {
  9. public:
  10.     explicit LazyValue(function<T()> init) { func_ = init; }
  11.  
  12.     bool HasValue() const {
  13.         return value_.has_value();
  14.     }
  15.     const T& Get() {
  16.         if (!HasValue()) {
  17.             value_ = func_();
  18.         }
  19.         return value_.value();
  20.     }
  21.  
  22. private:
  23.     function<T()> func_;
  24.     optional<T> value_;
  25. };
  26.  
  27. void UseExample() {
  28.     const string big_string = "Giant amounts of memory"s;
  29.  
  30.     LazyValue<string> lazy_string([&big_string] {
  31.         return big_string;
  32.     });
  33.  
  34.     assert(!lazy_string.HasValue());
  35.     assert(lazy_string.Get() == big_string);
  36.     assert(lazy_string.Get() == big_string);
  37. }
  38.  
  39. void TestInitializerIsntCalled() {
  40.     bool called = false;
  41.  
  42.     {
  43.         LazyValue<int> lazy_int([&called] {
  44.             called = true;
  45.             return 0;
  46.         });
  47.     }
  48.     assert(!called);
  49. }
  50.  
  51. int main() {
  52.     UseExample();
  53.     TestInitializerIsntCalled();
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement