Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. #include <iostream>
  2. #include <nlohmann/json.hpp>
  3. #include "boost/any.hpp"
  4.  
  5. using json = nlohmann::json;
  6.  
  7. namespace exchangable_data {
  8.  
  9.     class user_data {
  10.     public:
  11.  
  12.         user_data() : id(0) {}
  13.  
  14.         int id;
  15.     };
  16.  
  17.     class inserction : public user_data {
  18.     public:
  19.         inserction(std::string&& data,int position) : data(data),position(position) {}
  20.  
  21.         std::string data;
  22.         int position;
  23.     };
  24.  
  25.     class deletion : public user_data {
  26.     public:
  27.         deletion(int length,int position) : length(length),position(position) {}
  28.  
  29.         int position;
  30.         int length;
  31.     };
  32.  
  33.     void to_json(json& j,const deletion& d){
  34.         j = json{{"position",d.position},{"length",d.length}};
  35.     }
  36.  
  37.     void from_json(const json& j,deletion& d){
  38.         j.at("position").get_to(d.position);
  39.         j.at("length").get_to(d.length);
  40.     }
  41.  
  42.     void to_json(json& j, const inserction& i) {
  43.         j = json{{"data", i.data}, {"position", i.position}};
  44.     }
  45.  
  46.     void from_json(const json& j, inserction& i) {
  47.         j.at("data").get_to(i.data);
  48.         j.at("position").get_to(i.position);
  49.         j.at("id").get_to(i.id);
  50.     }
  51.  
  52.     void to_json(const json& j,user_data){
  53.  
  54.     }
  55.  
  56. }
  57.  
  58. int main() {
  59.     exchangable_data::inserction i1 = {"ciao!", 60};
  60.     exchangable_data::deletion d1 = {2,4};
  61.     exchangable_data::inserction i2 = {"ciao!", 60};
  62.     exchangable_data::deletion d2 = {2,4};
  63.  
  64.     std::vector<boost::any> vect;
  65.     vect.push_back(i1);
  66.     vect.push_back(d1);
  67.     vect.push_back(i2);
  68.     vect.push_back(d2);
  69.  
  70.  
  71.     json j;
  72.  
  73.     for (auto v : vect){
  74.  
  75.         json t;
  76.  
  77.         if (v.type() == typeid(exchangable_data::inserction)){
  78.             exchangable_data::inserction i = boost::any_cast<exchangable_data::inserction>(v);
  79.             t = i;
  80.         } else {
  81.             exchangable_data::deletion d = boost::any_cast<exchangable_data::deletion>(v);
  82.             t = d;
  83.         }
  84.  
  85.         j.push_back(t);
  86.     }
  87.  
  88.     std::cout << j;
  89.     return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement