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

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

#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

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航