innochenti
innochenti

Reputation: 1103

boost::serialization formatting

I have to use class Matrix4x4 from some 3rd party library, and I need to serialize it.

1. Is it ok to create header(3rdparty_serialization.h) that will contain all serialization that is needed for 3rd party libraries, like Matrix4x4:

namespace boost {
namespace serialization {

template<class Archive>
void serialize(Archive & ar, Matrix4x4 & m, const unsigned int version)
{
    for(size_t i = 0; i < 4;++i)
        for(size_t j = 0; j < 4;++j)
        {
            auto& e = m[i][j];
            ar & BOOST_SERIALIZATION_NVP(e);
        }
}

} // namespace serialization
} // namespace boost

2. Is this definition of function "serialize" for Matrix4x4 correct?

3. How to customize formatting of Matrix4x4 serialization? Now, I have output:

<m class_id="2" tracking_level="0" version="0">
    <e>1</e>
    <e>0</e>
    <e>0</e>
    <e>0</e>
    <e>0</e>
    <e>1</e>
    <e>0</e>
    <e>0</e>
    <e>0</e>
    <e>0</e>
    <e>1</e>
    <e>0</e>
    <e>0</e>
    <e>0</e>
    <e>0</e>
    <e>1</e>
</m>

I want something like this:

<m class_id="2" tracking_level="0" version="0">
        <e>1;0;0;0</e>
        <e>0;1;0;0</e>
        <e>0;0;1;0</e>
        <e>0;0;0;1</e>
</m>

or other more compact and readable form.

Upvotes: 1

Views: 477

Answers (2)

Robert Ramey
Robert Ramey

Reputation: 41

There a couple of ways to do this. The easiest way would be to make a special verision of serialize for xml_archive. This would keep the change from infecting other archive types. Try something like:

template<>
void save(boost::archive::xml_archive & ar, const Matrix4x4 & m, const unsigned int version)
{
    std::string e;
    for(size_t i = 0; i < 4;++i){
        for(size_t j = 0; j < 4;++j)
        {
            e +=  std::string(m[i][j]);
            e += ';';
        }
    }
    ar << BOOST_SERIALIZATION_NVP(e)
}

// similar for load

Robert Ramey

Upvotes: 3

user319799
user319799

Reputation:

1. Yes.

2. Yes, assuming Matrix is not within a namespace.

3. You could try serializing std::strings instead of individual elements. However, this is a bit wasteful since you will need to format and parse the strings. Also not optimal for size if you want to use e.g. binary_[io]archive.

Upvotes: 1

Related Questions