Speed
Speed

Reputation: 1434

How to serialize a 3D array with boost?

Okay, I recently switched to boost and I partitialy understand serializing simple objects or simple classes (the boost tutorial confuses me), but how can I serialize a 3D array which contains class members?

I have an array (std::vector) called TileList, which contains objects which are of a class Tile and class Tile contains nothing else than two variables, int TileID and int TilePassability.

I tried doing it as the Serialization tutorial does in the non obtrusive method and the STL Container method, but I just get a stack of errors in return. Can somebody explain how to do it properly? Thank you.

Upvotes: 0

Views: 1167

Answers (1)

Cat Plus Plus
Cat Plus Plus

Reputation: 129854

So I understand you have something like this (that's not really a 3D array, post the exact code you want to serialise if I misread you):

struct Tile {
    int id, passability;
};

std::vector<Tile> tileList;

Because std::vector is already serialisable through standard Boost.Serialization facilities, you only need to make Tile serialisable. The easiest way is to add a serialize member that does both the loading and saving.

struct Tile {
   int id, passability;

   template <typename Archive>
   void serialize(Archive& ar, const unsigned version) {
       ar & id;
       ar & passability;
   }
};

Aand that's about it, your type is now serialisable. Special things to be considered include class members being private — you need to add friend declaration for Boost.Serialization in this case, i.e.

class Tile {
    int id, passability;
    friend class boost::serialization::access;

    template <typename Archive>
    void serialize(Archive& ar, const unsigned version) {
        ar & id;
        ar & passability;
    }
public:
    Tile(int, int);
};

serialize member have to be a template (well, not really; but until you know the library a bit better, it have to be), so its entire body must be included within the class declaration (unless you use explicit instantiation, but that's also not something for beginners).

You can also split it into save and load members, but that's not useful until you start using versioning. It would look like this:

struct Tile {
    int id, passability;

    BOOST_SERIALIZATION_SPLIT_MEMBER()
    template <typename Archive>
    void save(Archive& ar, const unsigned version) { ... }
    template <typename Archive>
    void load(Archive& ar, const unsigned version) { ... }
};

That makes the type held by the vector serialisable. Serialising a vector itself is just archive & tileList.

Upvotes: 2

Related Questions