对标准库容器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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值