Advertisement
cepxuozab

BuilderJson

Jun 27th, 2024
878
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3. #include <set>
  4. #include <string>
  5.  
  6. class Json { };
  7.  
  8. class Builder {
  9.     class BaseContext;
  10.     class DictValueContext;
  11.     class ArrayItemContext;
  12. public:
  13.     Builder()=default;
  14.     DictValueContext StartDict();
  15.     ArrayItemContext StartArray();
  16.     BaseContext EndDict();
  17.     BaseContext EndArray();
  18.  
  19. private:
  20.     Json* json;
  21.     class BaseContext {
  22.     public:
  23.         BaseContext(Builder& builder)
  24.             : builder_(builder)
  25.         {
  26.         }
  27.         DictValueContext StartDict() {
  28.             return builder_.StartDict();
  29.         }
  30.         ArrayItemContext StartArray() {
  31.             return builder_.StartArray();
  32.         }
  33.         BaseContext EndDict() {
  34.             return builder_.EndDict();
  35.         }
  36.         BaseContext EndArray() {
  37.             return builder_.EndArray();
  38.         }
  39.  
  40.     private:
  41.         Builder& builder_;
  42.     };
  43.  
  44.     class DictValueContext : public BaseContext {
  45.     public:
  46.         DictValueContext(BaseContext base)
  47.             : BaseContext(base)
  48.         {
  49.         }
  50.         BaseContext EndArray() = delete;
  51.         DictValueContext StartDict() = delete;
  52.         ArrayItemContext StartArray() = delete;
  53.     };
  54.  
  55.     class ArrayItemContext : public BaseContext {
  56.     public:
  57.         ArrayItemContext(BaseContext base) : BaseContext(base) {}        
  58.         BaseContext EndDict() = delete;
  59.     };
  60. };
  61.  
  62. Builder::DictValueContext Builder::StartDict() {
  63.     return BaseContext{ *this };
  64. }
  65.  
  66. Builder::ArrayItemContext Builder::StartArray() {  
  67.     return BaseContext{ *this };
  68. }
  69.  
  70. Builder::BaseContext Builder::EndDict() {    
  71.     return *this;
  72. }
  73.  
  74. Builder::BaseContext Builder::EndArray() {
  75.         return *this;
  76. }
  77.  
  78. int main(){
  79.     auto doc = Builder().StartArray().EndDict();
  80. }
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement