Advertisement
robn

Untitled

Dec 24th, 2012
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. // this is the thing that we build up with data that we want to save
  2. class SerializedObject {
  3. public:
  4.     SerializedObject();
  5.  
  6.     std::string ToString() const;
  7.  
  8.     Set(const std::string &k, int v);
  9.     Set(const std::string &k, double v);
  10.     Set(const std::string &k, const SerializedObject &v);
  11. };
  12.  
  13.  
  14. // some random class
  15. class Something {
  16. public:
  17.     // regular constructor
  18.     Something(...);
  19.  
  20.     // construct from saved data
  21.     Something(const SerializedObject &so);
  22.  
  23.     // return data for save
  24.     SerializedObject Serialize() const;
  25. };
  26.  
  27.  
  28. // Serialize() method for some class that has a field that can be serialized
  29. SerializedObject Thing::Serialized() const {
  30.     SerializedObject so;
  31.     so.Set("int", m_int);                        // int m_int
  32.     so.Set("double", m_double);                  // double m_double
  33.     so.Set("something", m_something.Serialize(); // Something m_something
  34.     return so;
  35. }
  36.  
  37.  
  38. // the last one sucks. I want to write:
  39. //   so.Set("something", m_something)
  40. // and it calls its Serialize automatically
  41.  
  42. class Serializable {
  43. public:
  44.     virtual SerializerObject Serialize() const = 0;
  45. };
  46.  
  47. class SerializerObject {
  48.     ...
  49.     Set(const std::string &k, const SerializedObject &v);
  50.     void Set(const std::string &k, const Serializable &v) {
  51.         Set(k, v.Serialize());
  52.     }
  53.     ...
  54. };
  55.  
  56.  
  57. class Something : public Serializable {
  58.     ...
  59.     SerializedObject Serialize() const;
  60. };
  61.  
  62.  
  63. // except now we have a circular dependency, which can't be resolved by
  64. // forward declarations because there's no pointers or references involved
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement