简体   繁体   English

使用Boost.Serialization时更改STL容器的序列化

[英]Changing serialization of STL containers when using Boost.Serialization

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. 我想以某种方式扩展Boost序列化库,以便STL集合以与Boost序列化库所提供格式不同的格式保存到XML档案中。

If I am correct all STL containers pass the following function during serialization: 如果我是正确的,则所有STL容器在序列化过程中都会通过以下功能:

// <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 . 因此,我尝试为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. 但是它不调用我的函数,而是调用Boost提供的函数。 What do I have to do/change to make my serialization of STL containers work? 为了使STL容器的序列化工作,我必须做什么/更改?

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM