shushus

Спринт 12. Логическая константность и mutable.

Apr 6th, 2023
383
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 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) : function_(init) {}
  11.  
  12.     bool HasValue() const {
  13.         return value_.has_value();
  14.     }
  15.    
  16.     const T& Get() const {
  17.        
  18.         if (HasValue()) {
  19.             return value_.value();    
  20.         } else {
  21.              value_ = function_();
  22.              return value_.value();
  23.          }
  24.     }
  25.  
  26. private:
  27.     function<T()> function_;
  28.     mutable optional<T> value_ = nullopt;
  29. };
  30.  
  31. void UseExample() {
  32.     const string big_string = "Giant amounts of memory"s;
  33.  
  34.     LazyValue<string> lazy_string([&big_string] {
  35.         return big_string;
  36.     });
  37.  
  38.     assert(!lazy_string.HasValue());
  39.     assert(lazy_string.Get() == big_string);
  40.     assert(lazy_string.Get() == big_string);
  41. }
  42.  
  43. void TestInitializerIsntCalled() {
  44.     bool called = false;
  45.  
  46.     {
  47.         LazyValue<int> lazy_int([&called] {
  48.             called = true;
  49.             return 0;
  50.         });
  51.     }
  52.     assert(!called);
  53. }
  54.  
  55. int main() {
  56.     UseExample();
  57.     TestInitializerIsntCalled();
  58. }
Advertisement
Add Comment
Please, Sign In to add comment