How can we serialize an arbitrary class?

Given this class:

1
2
3
4
5
6
7
8
9
10
11
struct Address
{
	string street;
	string city;
       int suite;

       friend ostream& operator<<(ostream& os, Address& adr)
      {
             return os << adr.street << adr.city << adr.suite;
      }
};


how can I serialize/deserialize it into a file or a ostringstream?
What can I use to separate strings? Upon reading, the spaces will become the separators and that is not what I need...

Regards,
Juan
Last edited on
> What can I use to separate strings?

For a simple, always same number of fields situation like this, just use new lines. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <sstream>

struct address
{
    std::string street ;
    std::string city ;
    int suit = 0 ;

    friend std::ostream& operator<< ( std::ostream& stm, const address& addr )
    { return stm << addr.street << '\n' << addr.city << '\n' << addr.suit << '\n' ; }

    friend std::istream& operator>> ( std::istream& stm, address& addr )
    {
        std::getline( stm >> std::ws, addr.street ) ; // skip empty lines
        std::getline( stm, addr.city ) ;
        return stm >> addr.suit ;
    }
};

int main()
{
    const address a { "Viamonte", "Buenos Aires", 430 },
                  b { "Universitetskaya Emb", "Saint Petersburg", 199034 } ;

    std::stringstream stm ;
    stm << a << "\n\n\n" << b << '\n' ;

    address c, d ;
    stm >> c >> d ;

    std::cout << c << '\n' << d ;
}

http://coliru.stacked-crooked.com/a/028d3193140ee6fa

Things are a bit more complicated if the fields themselves may contain new lines;
for some commonly used formats, see: http://www.catb.org/esr/writings/taoup/html/ch05s02.html
Thanks for this simple solution. I am going to investigate boost::serializable for a more industrial solution.
Topic archived. No new replies allowed.