对标准库容器Serialize的模板函数,针对指针元素,支持各种智能指针!

#ifndef mslk_utility_h_12345

#define mslk_utility_h_12345

#include <boost/type_traits.hpp> // for boost::type_traits

#include <cassert>     // for assert

#include <vector>     // for std::vector

#include <memory>     // for std::auto_ptr

#include <afxtempl.h>    // for mfc::collect

namespace detail{ /// support smart_ptr

template<bool bIsPtr>

struct SerialzeElem   // pointer

{

 template<typename T>

 static void do_write(CArchive &ar,T const& op)

 {

  CObject *pOb = dynamic_cast<CObject*>(op);

  assert(NULL != pOb);

  ar<<pOb;

 }

 template<typename T>

 static void do_read(CArchive &ar,T& op)

 {

  CObject *pOb=NULL;

  ar>>pOb;

  op = dynamic_cast<T>(pOb);

  assert(NULL != op);

 }

};

template<>

struct SerialzeElem<false> // smart_ptr

{

 template<typename T>

 static void do_write(CArchive &ar,T const& sp)

 {

  CObject *pOb = dynamic_cast<CObject*>(sp.get());

  assert(NULL != pOb);

  ar<<pOb;

 }

 template<typename T>

 static void do_read(CArchive &ar,T& sp)

 {

  CObject *pOb=NULL;

  ar>>pOb;

  T::element_type* p = dynamic_cast<T::element_type*>(pOb); 

  assert(NULL != p);  

  sp = T(p);

 }

};

} // end: detail

// 10.26 update: 添加特性,支持元素类型为Smart_ptr的集合

// 通用对象指针的serialize

template<typename T> // T ==> std::list<…>;std::vector<…>

void CommonObjectPointerCollectSerialize( CArchive &ar, T &refAnyDataCollect ) 

{

 DWORD dwCount;

 if (ar.IsStoring())

 {

  dwCount = refAnyDataCollect.size();  

  ar<<dwCount;

  assert(dwCount>=0);

  

  T::iterator itBeg(refAnyDataCollect.begin()),itEnd(refAnyDataCollect.end());

  for(; itBeg!=itEnd; ++itBeg)

  {

   sw::detail::SerialzeElem<boost::is_pointer<T::value_type>::value >::do_write(ar,*itBeg);

  }

 }

 else

 {

  ar>>dwCount; 

  assert(dwCount>=0);

  while (dwCount--)

  {

   T::value_type v;

   sw::detail::SerialzeElem<boost::is_pointer<T::value_type>::value >::do_read(ar,v);

   refAnyDataCollect.push_back( v );

  }

 } 

}

#endif  //mslk_utility_h_12345

阅读更多
个人分类: C++
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭