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. Ubuntu的软件更新常识--添加软件源与ppa源

    加入ppa源的命令: sudo add-apt-repository ppa:user/ppa-name 删除ppa源的命令: sudo add-apt-repository -r ppa:user/ ...

  2. js post

    在进行html5页面的设计时,希望用户加载完成页面后,进行交互时只改变其中的某些元素的内容,这样更像本地APP的呈现效果,但是HTML中的post.get如果使用submit进行提交的话会直接使用返回 ...

  3. Angular2 Observable 可观察对象

    可观察对象支持在应用中的发布者和订阅者之间传递消息.在需要进行事件处理,异步编程和处理多值的时候,可观察对象相对其他技术有显著的优点. 可观察对象是声明式的 —— 也就是说,虽然你定义了一个用于发布值 ...

  4. WPF 附加事件

    在WPF中有许多控件有他们自己的特殊的事件.按钮就是一个例子——它添加了 Click 事件,而其他任何类都没有定义该事件. 这回导致两难的境地.假设在 StackPanel 面板中包装了一堆按钮,并且 ...

  5. 编程之美 set 7 求数组中的最长递增子序列

    解法 1. 假设在目标数组 array[] 的前 i 个元素中, 最长递增子序列的长度为 LIS[i] 那么状态转移方程为 LIS[i] = max(1, LIS[k]+1) array[i+1] & ...

  6. Fragment之间传数据

    1.用bundle存Bundle bundle = new Bundle();bundle.putString("cid1", classList.get(i).getId()); ...

  7. c++11 类型推断

    自动类型推断 当编译器能够在一个变量的声明时候就推断出它的类型,那么你就能够用auto关键字来作为他们的类型: auto x = 1; 编译器当然知道x是integer类型的.所以你就不用int了.接 ...

  8. 【BZOJ2095】[Poi2010]Bridges 动态加边网络流

    [BZOJ2095][Poi2010]Bridges Description YYD为了减肥,他来到了瘦海,这是一个巨大的海,海中有n个小岛,小岛之间有m座桥连接,两个小岛之间不会有两座桥,并且从一个 ...

  9. angular 4 路由变化的时候实时监测刷新组件

    当路由变化的时候刷新组件 比如说要刷新header组件 在header.ts里 import {Router, NavigationEnd} from "@angular/router&qu ...

  10. 160317(一)、在非action中获取request

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes() ...