#include "stdafx.h"
#include <iostream>
#include <boost/any.hpp>
#include <boost/format.hpp>
using namespace std;
#define PRINT(xxx) ( std::cout << boost::format("%-20s = ") % (#xxx) << (xxx) << std::endl)
int main(int argc, char const *argv[])
{
/* 1.基本用法 */
puts("1.基本用法");
boost::any a(26);
//获取原对象
cout<< " boost::any_cast<int>(a): "<<boost::any_cast<int>(a) << endl;
a =55;
//获取原对象的引用
int& b = boost::any_cast<int&>(a);
b = 1777;
cout << b<<boost::any_cast<int>(a) << endl;
//获取原对象的指针
int* ss = boost::any_cast<int>(&a);
*ss = 66;
cout << *ss <<" "<< boost::any_cast<int>(a) << endl;
//获取原对象的类型信息
PRINT(a.type().name());
//检测any中是否保存了对象
if (a.empty() == true) {
cout << "true" << endl;
}
else {
cout << "false" << endl;
}
/**************************************************************************/
/*二,智能指针。 不能用any保存堆上的原始的指针,会造成内存泄露,应使用智能指针*/
puts("二,智能指针");
//下面这样做会造成内存泄露
int* p = new int(2);
boost::any ptr_any(p);
int* tmp = boost::any_cast<int*>(ptr_any);
PRINT(*tmp);
//应当使用智能指针,而且只能使用shared_ptr,因为scoped_ptr不能被复制
//这样在any析构时,会调用shared_ptr的析构函数,释放其持有的资源
boost::any shared_any(boost::shared_ptr<int>(new int(3)));
boost::shared_ptr<int> p_shared = boost::any_cast<boost::shared_ptr<int> >(shared_any);
PRINT(*p_shared);
/**************************************************************************/
//三,辅助函数:
puts("三,辅助函数");
//std::string str("hai tao gao ruan");
string str = "hai tao gao ruan";
boost::any xxx(str);
string mmm = boost::any_cast<string>(xxx);
cout <<mmm << endl;
/**************************************************************************/
//四,用于容器:
puts("四,用于容器");
std::vector<boost::any> vec{
1,
std::string("你好!"),
1.414,
boost::shared_ptr<std::string>(new std::string("end"))
};
PRINT(boost::any_cast<int>(vec[0]));
PRINT(boost::any_cast<std::string&>(vec[1]));
PRINT(boost::any_cast<double>(vec[2]));
boost::shared_ptr<std::string> mm = boost::any_cast<boost::shared_ptr<std::string>>(vec[3]);
std::cout << *mm << std::endl;
PRINT(*boost::any_cast<boost::shared_ptr<std::string>>(vec[3]));
getchar();
return 0;
}
一定要注意:
FR:海涛高软(QQ技术交流群:386476712)