0

I want to extend the Boost Serialization library in such a way that STL collections are saved to XML archives in a different format than the one provided by the Boost Serialization library.

If I am correct all STL containers pass the following function during serialization:

// <boost/serialization/collections_save_imp.hpp>

namespace boost{ namespace serialization { namespace stl {

template<class Archive, class Container>
inline void save_collection(Archive & ar, const Container &s)
{
    /* ... */
}

} } }

So I tried to overload this function for the xml_oarchive. Here is a little example of my approach:

#include <iostream>
#include <vector>

#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/vector.hpp>

namespace boost { namespace serialization { namespace stl {

template< typename Container >
inline void save_collection( boost::archive::xml_oarchive& ar, Container const& s )
{
  /* My serialization */
}

} } }

int main()
{
  {
    boost::archive::xml_oarchive ar( std::cout );

    std::vector< int > x;

    x.push_back( -1 );
    x.push_back(  1 );
    x.push_back( 42 );
    x.push_back(  0 );

    ar << BOOST_SERIALIZATION_NVP( x );
  }

  return 0;
}

It compiles and runs. But it does not call my function, but the one provided by Boost. What do I have to do/change to make my serialization of STL containers work?

user2436830
  • 439
  • 3
  • 5

1 Answers1

0

Finally I came up with this solution to my problem:

#include <iostream>
#include <vector>

namespace boost { namespace archive { class xml_oarchive; } }

namespace boost { namespace serialization { namespace stl { 


  /* Two template parameters are needed here because at the caller side
   * a function with two template parameters is explicitly requested. */
  template< typename, typename Container >
  void save_collection( boost::archive::xml_oarchive&, Container const& )
  {
      /* ... */
  }

} } }
/* Note that this is before the boost includes. */

#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/vector.hpp>


int main()
{
  {
    boost::archive::xml_oarchive ar( std::cout );

    std::vector< int > x;

    x.push_back( -1 );
    x.push_back(  1 );
    x.push_back( 42 );
    x.push_back(  0 );

    ar << BOOST_SERIALIZATION_NVP( x );
  }

  return 0;
}
user2436830
  • 439
  • 3
  • 5