Serialization

I am trying to learn about serialization so I can save class instances and containers without creating complicated file structures. This code seems like it should work but I get the following error: incomplete type 'boost::STATIC_ASSERTION_FAILURE<false>' used in nested name specifier size of array has non-integral type'<type error>'
This error occurs at the line where the class is sent to the ostream, and the error redirects me to oserializer.hpp. I'm kind of stuck here. I know the boost library works is installed properly, I have used many of the date and time functions before on my system. Any ideas? Here is my code:
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
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include<fstream>
#include<vector>
using namespace std;

class myclass{
      private:
              friend class boost::serialization::access;
              template<class Archive>
              void serialize(Archive & ar, const unsigned int version)
              {
                   ar & x;
                   ar & str;
                   }
              int x;
              string str;
      public:
                 myclass(){
                    x=12345;
                    str="This is a string.";
                                 }
};             
int main(){
    ofstream output("ints.dat");
    myclass instance;
    {boost::archive::text_oarchive outarc(output);
    outarc<<instance;
}
return 0;
}
Last edited on
Apparently, the object being serialized needs to be const. You could trick the compiler into thinking the object is const:
outarc <<*(const myclass *)&instance;
Thanks a lot, that was a neat trick, works great. I'd like to understand exactly what is going on with this code though, if you don't mind. A pointer to a constant instance of a myclass pointer to a reference to my previous instance of the class? I've never seen anything like this before.
It's simply casting the object to be const. It's nothing special.

1) Get the address of the object
2) Cast the address such that the compiler treats the object pointed to as const
3) Reference the address to put it back into an object, which is now treated as const
I see, very nice. I guess this will work with other variables and not just objects, awesome. Thanks both of you guys, learned a lot today.
Topic archived. No new replies allowed.