boost::any 具体使用

#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)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值