boost::any可以存放任何类型的C++类型,也可以是用户自定义的类型。非常方便,可以很方便的满足在运行过程中判断数据类型,从而进行相关的操作。

函数原型:

// In header: <boost/any.hpp>

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

成员函数说明:

Boost::Any的实现比较简单,Any拥有一个模版构造函数,这使他可以接受任何类型的对象。真正的变量内容被封装在嵌套类类型的成员变量中,并且在嵌套类中使用typeid来记录真正的类型信息。

1) any& swap(any& other);交换存在两个 any 对象中的值。
  2) any& operator=(const any& other);如果any实例非空,则丢弃所存放的值,并存入other值的拷贝。
  3)template<typename ValueType>  any& operator=(const ValueType& value);如果any实例非空,则丢弃所存放的值,并存入 value 的一份拷贝,value可以是任意符合any要求的类型。
  4) bool empty() const;给出any实例当前是否有值,不管是什么值。因而,当any持有一个指针时,即使该指针值为空,则 empty也返回 false 。
  5) const std::type_info& type() const;给出所存值的类型。如果 any 为空,则类型为 void.
  6) any_cast()将any类型转化为真实的类型,如果是指针返回的可能是空指针,如果非指针,则可能会抛出异常。

三 实例

1)简单实例以及调用常用的成员函数:

#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include "boost/any.hpp" class A
{
public:
void some_function()
{
std::cout << "A::some_function()\n";
}
};
class B
{
public:
void some_function()
{
std::cout << "B::some_function()\n";
}
}; void print_any(boost::any& a)
{
if (A* pA=boost::any_cast<A>(&a))
{
pA->some_function();
}
else if (B* pB=boost::any_cast<B>(&a))
{
pB->some_function();
}
else
{
try
{
std::cout << boost::any_cast<std::string>(a) << '\n';
}
catch(boost::bad_any_cast&)
{
std::cout << "Oops!\n";
}
}
} int main()
{
std::cout << "Example of using any.\n\n";
std::vector<boost::any> store_anything;
store_anything.push_back(A());
store_anything.push_back(B());
// 我们再来,再加一些别的东西
store_anything.push_back(std::string("This is fantastic! "));
store_anything.push_back();
store_anything.push_back(std::make_pair(true, 7.92));
std::for_each( store_anything.begin(), store_anything.end(), print_any); std::cout << "Example of using any member functions\n\n";
boost::any a1();
boost::any a2(std::string(""));
boost::any a3;
std::cout << "a3 is ";
if (!a3.empty())
{
std::cout << "not empty\n ";
}
std::cout << "empty\n";
a1.swap(a2);
try
{
std::string s=boost::any_cast<std::string>(a1);
std::cout << "a1 contains a string: " << s << "\n";
}
catch(boost::bad_any_cast& e)
{
std::cout << "I guess a1 doesn't contain a string!\n";
}
if (int* p=boost::any_cast<int>(&a2))
{
std::cout << "a2 seems to have swapped contents with a1: " << *p << "\n";
}
else
{
std::cout << "Nope, no int in a2\n";
}
if (typeid(int)==a2.type())
{
std::cout << "a2's type_info equals the type_info of int\n";
} } )解决类似与map但是可以映射到各种不同的类型的问题: #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include "boost/any.hpp"
class property
{
boost::any value_;
std::string name_;
public:
property(const std::string& name,const boost::any& value)
: name_(name),value_(value) {}
std::string name() const { return name_; }
boost::any& value() { return value_; }
friend bool operator<(const property& lhs, const property& rhs)
{return lhs.name_<rhs.name_;}
};
void print_names(const property& p)
{
std::cout << p.name() << "\n";
}
int main()
{
std::cout << "Example of using any for storing properties.\n";
std::vector<property> properties;
properties.push_back( property("B", ));
properties.push_back( property("A", std::string("Thirty something")));
properties.push_back(property("C", 3.1415));
std::sort(properties.begin(),properties.end());
std::for_each(properties.begin(), properties.end(), print_names);
std::cout << "\n";
std::cout << boost::any_cast<std::string>(properties[].value()) << "\n";
std::cout << boost::any_cast<int>(properties[].value()) << "\n";
std::cout << boost::any_cast<double>(properties[].value()) << "\n";
}

四 注意

1)Any中如果是指针,要注意指针的最后的释放,最好使用shared_ptr来管理。
2)Any中如果是指针,如果Any.isempty()返回false,但是any所包含的指针仍可能是无效的。
3)Any中如果是指针,则在调用any_cast()转化的过程中不会抛出异常,但是如果是一般变量或引用的话,类型不正确会抛出boost::bad_any_cast异常。

五 参考

1)Beyond the C++ Standard Library: An Introduction to Boost
2)boost在线document

参考:http://www.cppblog.com/mzty/archive/2007/08/16/30156.html

any类实现:

boost::any类并不是一个模板类,这可以大大的方便上层应用的使用,它会自动化的类型转换。核心就是any类中,包含一个模板类holder的基类placeholder指针,而placeholder却不是模板类,这样就可以被any类使用了。

具体的如下面所示:

http://www.cnblogs.com/wuerping/articles/116414.html

更多:http://blog.csdn.net/hityct1/article/details/4186962

boost::any 用法的更多相关文章

  1. 初识boost之boost::share_ptr用法

    boost中提供了几种智能指针方法:scoped_ptr shared_ptr intrusive_ptr weak_ptr,而标准库中提供的智能指针为auto_ptr. 这其中,我最喜欢,使用最多的 ...

  2. [转] boost::function用法详解

    http://blog.csdn.net/benny5609/article/details/2324474 要开始使用 Boost.Function, 就要包含头文件 "boost/fun ...

  3. boost::thread用法

    最近在做一个消息中间件里面涉及到多线程编程,由于跨平台的原因我采用了boost线程库.在创建线程时遇到了几种线程创建方式现总结如下: 首先看看boost::thread的构造函数吧,boost::th ...

  4. boost::share_ptr用法

    boost中提供了几种智能指针方法:scoped_ptr shared_ptr intrusive_ptr weak_ptr,而标准库中提供的智能指针为auto_ptr. 这其中,我最喜欢,使用最多的 ...

  5. boost::function用法详解

    要开始使用 Boost.Function, 就要包含头文件 "boost/function.hpp", 或者某个带数字的版本,从 "boost/function/func ...

  6. Boost::split用法详解

    工程中使用boost库:(设定vs2010环境)在Library files加上 D:\boost\boost_1_46_0\bin\vc10\lib在Include files加上 D:\boost ...

  7. boost::algorithm用法详解之字符串关系判断

    http://blog.csdn.net/qingzai_/article/details/44417937 下面先列举几个常用的: #define i_end_with boost::iends_w ...

  8. boost::fucntion 用法详解

    转载自:http://blog.csdn.net/benny5609/article/details/2324474 要开始使用 Boost.Function, 就要包含头文件 "boost ...

  9. [转] boost:lexical_cast用法

    转载地址:http://www.habadog.com/2011/05/07/boost-lexical_cast-intro/ 一.lexical_cast的作用lexical_cast使用统一的接 ...

随机推荐

  1. Spring的一种拦截器SimpleUrlHandlerMapping

    spring的一种拦截器,用于在XML文件中配置以拦截url,它是以map映射的方式进行拦截.映射是从前台urls到具体后台的beans.同时支持到bean实例和bean名称的映射,后者要求非单实例控 ...

  2. Java的图形界面依然是跨平台的

    Awt:抽象窗口工具箱,它由三部分组成: ①组件:界面元素: ②容器:装载组件的容器(例如窗体): ③布局管理器:负责决定容器中组件的摆放位置. 图形界面的应用分四步: ① 选择一个容器: ⑴wind ...

  3. 【BZOJ】1636: [Usaco2007 Jan]Balanced Lineup(rmq+树状数组)

    http://www.lydsy.com/JudgeOnline/problem.php?id=1636 (我是不会说我看不懂题的) 裸的rmq.. #include <cstdio> # ...

  4. notepad++程序员开发插件

    1. sftp 2. explore 3. XBrackets 括号自动补全(引号,方括号)

  5. jQuery秒表、闹钟、计时器和报警插件

    jQuery秒表.闹钟.计时器和报警插件 http://www.sucaihuo.com/jquery/8/896/demo/

  6. POJ2139 Six Degrees of Cowvin Bacon [Floyd]

    水题,随手敲过 一看就是最短路问题,a,b演同一场电影则他们的距离为1 默认全部两两原始距离无穷,到自身为0 输入全部数据处理后floyd 然后照它说的求平均分离度 再找最小的,×100取整输出 #i ...

  7. 剑指 offer set 24 扑克牌的顺子

    题目 从扑克牌中任意抽取出 5 张牌, 判断是不是顺子, 并且大小王可以看成任意的数字 思路 1. 把大小王当做 0 插入到数组中, 然后对数组排序 2. 统计相邻两个数之间的空隙数, 若空隙数大于 ...

  8. dubbo项目实战代码展示

    最近公司项目使用dubbo服务,于是就去网上搜索关于dubbo的相关资料,真的很多,但是对于很多人并不是很了解框架或者 不是太适合新手的片段代码,于是我就根据项目的相关内容把dubbo部分单独切出来, ...

  9. JZOJ.5306【NOIP2017模拟8.18】棋盘游戏

    Description 这个游戏上在一个无限大的棋盘上, 棋盘上只有一颗棋子在位置(x,y)(x,y>=0)棋盘的左下角是(0,0)Amphetamine每次都是第一个移动棋子,然后Amphet ...

  10. visual studio 常识

    去掉 引用提示 文本编辑器=>所有语言=>codelens