一直被超越,从未被模仿

Craft Life, Don't let life Craft you.

Boost.Any

Examples

#include <list>
#include <boost/any.hpp>

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

void append_int(many & values, int value)
{
    boost::any to_append = value;
    values.push_back(to_append);
}

void append_string(many & values, const std::string & value)
{
    values.push_back(value);
}

void append_char_ptr(many & values, const char * value)
{
    values.push_back(value);
}

void append_any(many & values, const boost::any & value)
{
    values.push_back(value);
}

void append_nothing(many & values)
{
    values.push_back(boost::any());
}

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;
    }
}

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) << std::endl;
}

Reference

Header <boost/any.hpp>

namespace boost {
  class bad_any_cast;
  class any;
  void swap(any &, any &);
  template<typename T> T any_cast(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 *);
}

Class any

class any {
public:
  // construct/copy/destruct
  any();
  any(const any &);
  any(any &&);
  template<typename ValueType> any(const ValueType &);
  template<typename ValueType> any(ValueType &&);
  any & operator=(const any &);
  any & operator=(any &&);
  template<typename ValueType> any & operator=(const ValueType &);
  template<typename ValueType> any & operator=(ValueType &&);
  ~any();

  // modifiers
  any & swap(any &);

  // queries
  bool empty() const;
  void clear();
  const std::type_info & type() const;
};



阅读更多
文章标签: Boost Boost.Any
个人分类: Boost
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Boost.Any

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭