boost::any 的使用【转】

1,对于 any 所能 “接受” 的值类型 (ValueType) 有如下的要求:
 
   * 该 ValueType 是 CopyConstructible 的;

   * 该 ValueType 还有可选的 Assignable 的。而对于很强的异常安全保证的话,就需要所有形式的 Assignment;

   * 析构函数 upholds the no-throw exception-safety guarantee.
 
2,下面是一些常用的模板函数,及类型声明:
 

    namespace boost {
     class bad_any_cast;
     class any;
     template<typename T> T any_cast(any &);
     template<typename T> T any_cast(const any &);
     template<typename ValueType> const ValueType * any_cast(const any *);
     template<typename ValueType> ValueType * any_cast(any *);
    }

3,any 类的摘要

    class any {
    public:
     // construct/copy/destruct

     any();
     any(const any &);
     template<typename ValueType> any(const ValueType &);
     any & operator=(const any &);
     template<typename ValueType> any & operator=(const ValueType &);
     ~any();
    
     // modifiers

     any & swap(any &);
    
     // queries

     bool empty() const;
     const std::type_info & type() const;
    };

3,示例:


#include <vector>
#include <string>
#include <iostream>
#include <boost/any.hpp>

using boost::any_cast;
typedef std::vector<boost::any> many;

// 向容器中插入 int 型值
void append_int(many & values, int value)
{
    boost::any to_append = value;
    values.push_back(to_append);
}

// 向容器中插入 string 型值
void append_string(many & values, const std::string & value)
{
    values.push_back(value);
}

// 向容器中插入 const char* 型值
void append_char_ptr(many & values, const char * value)
{
    values.push_back(value);
}

// 向容器中插入 const boost::any& 型值
void append_any(many & values, const boost::any & value)
{
    values.push_back(value);
}

// 什么都没有,就是一个空值
void append_nothing(many & values)
{
    values.push_back(boost::any());
}

// ----- 下面也演示了一些与 predicates 相关方法

// 是否为空值
bool is_empty(const boost::any & operand)
{
    return operand.empty();        
}

// 查看类型值
bool is_int(const boost::any & operand)
{
    return operand.type() == typeid(int);
}

// 注意指针类型转型的异常处理
bool is_char_ptr(const boost::any & operand)
{
    try
    {
        any_cast<const char *>(operand);
        return true;
    }
    catch(const boost::bad_any_cast &)
    {
        return false;
    }
}

// 对于其他类,直接使用 any 转型
bool is_string(const boost::any & operand)
{
    return any_cast<std::string>(&operand);
}

// 统计每种类型的个数
void count_all(many & values, std::ostream & out)
{
    out << "#empty == "
        << std::count_if(values.begin(), values.end(), is_empty) << std::endl;
    out << "#int == "
        << std::count_if(values.begin(), values.end(), is_int) << std::endl;
    out << "#const char * == "
        << std::count_if(values.begin(), values.end(), is_char_ptr) << std::endl;
    out << "#string == "
        << std::count_if(values.begin(), values.end(), is_string
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值