Advertisement
gediminasel

Untitled

Nov 18th, 2024
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. MyObject: type = {
  2.     // some more fields
  3.     public url: std::string;
  4.     public operator=:(out this, url_: std::string) = {
  5.         this.url = url_;
  6.     }
  7.     public operator=:(out this, in that) = {
  8.         this.url = that.url;
  9.     }
  10. }
  11.  
  12. CachingMyObjectAccessor: type = {
  13.     public operator=:(out this, obj_: *MyObject) = {
  14.         this.obj = obj_;
  15.         this.parsed_url = std::nullopt;
  16.     }
  17.     public get_domain: (inout this) -> std::string_view = {
  18.         this.parse_url();
  19.         return std::get<1>(parsed_url*);
  20.     }
  21.     public get_path: (inout this) -> std::string_view = {
  22.         this.parse_url();
  23.         return std::get<2>(parsed_url*);
  24.     }
  25.     private parse_url: (inout this) = {
  26.         if (!parsed_url.has_value()) {
  27.             // some expensive code
  28.             s := std::string_view(obj*.url);
  29.             i := s.find("//");
  30.             j := s.find("/", i+2);
  31.             this.parsed_url = (s.substr(0, i), s.substr(i+2, j-i-2), s.substr(j));
  32.         }
  33.     }
  34.     obj: *MyObject;
  35.     parsed_url: std::optional<std::tuple<std::string_view, std::string_view, std::string_view>>;
  36. }
  37.  
  38. main: () -> int = {
  39.     o: MyObject = ("http://a.b/c/d/e");
  40.     a: CachingMyObjectAccessor = (o&);
  41.     // oo := o;  // uncommenting this moves out of o breaking the accessor
  42.     std::print("domain: {} path: {}", a.get_domain(), a.get_path());
  43.     _ = a;
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement