原文地址:
http://cjbskysea.blogbus.com/logs/61808617.html
1.boost::any
boost::any
是一种通用的数据类型,可以将各种类型包装后统一放入容器内,最重要的它是类型安全的。有点象
COM
里面的
variant
。
使用方法:
any::type()
返回包装的类型
any_cast
可用于
any
到其他类型的转化
#include <boost/any.hpp>
void
test_any()
typedef
std::vector<boost::any> many;
many a;
a.push_back(2);
a.push_back(string(
"test"
));
for
(unsigned
int
i=0;i<a.size();++i)
cout<<a[i].type().name()<<endl;
int
result = any_cast<
int
>(a[i]);
cout<<result<<endl;
catch
(boost::bad_any_cast & ex)
cout<<
"cast error:"
<<ex.what()<<endl;
string s(
"This is , a ,test!"
);
boost::tokenizer<> tok(s);
for
(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg)
cout << *beg <<
" "
;
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
void
test_serialization()
boost::archive::text_oarchive to(cout , boost::archive::no_header);
int
i = 10;
string s =
"This is a test "
;
to & i;
to & s;
ofstream f(
"test.xml"
);
boost::archive::xml_oarchive xo(f);
xo & BOOST_SERIALIZATION_NVP(i) & BOOST_SERIALIZATION_NVP(s);
boost::archive::text_iarchive ti(cin , boost::archive::no_header);
ti & i & s;
cout <<
"i="
<< i << endl;
cout <<
"s="
<< s << endl;
test x;
boost::function<
int
(test*,
int
,
int
)> f2;
f2 = &test::foo;
cout <<
"f2(5,3)="
<<f2(&x,5,3)<<endl;
9.boost::shared_ptr
boost::shared_ptr
就是智能指针的实现,不象
std::auto_ptr
,它是可以
stl
的容器一起使用的,非常的方便。
#include <boost/shared_ptr.hpp>
class
Shared
public
:
Shared()
cout <<
"ctor() called"
<<endl;
Shared(
const
Shared & other)
cout <<
"copy ctor() called"
<<endl;
~Shared()
cout <<
"dtor() called"
<<endl;
Shared & operator = (
const
Shared & other)
cout <<
"operator = called"
<<endl;
void
test_shared_ptr()
typedef
boost::shared_ptr<Shared> SharedSP;
typedef
vector<SharedSP> VShared;
VShared v;
v.push_back(SharedSP(
new
Shared()));
v.push_back(SharedSP(
new
Shared()));