dos2unix

记性不好,需要一个blog。

boost::any

Any简介

Any库提供一个类型, any, 它允许存入任意类型且稍后取回,而不损失类型安全性。它有点象是可变类型的化合物:它可以持有任意类型,但你必须知道类型才能取回值。可以把  any 看作为上锁的安全性。没有正确的钥匙,你不能进入其中。any 对它所保存
的类型有以下要求:
  CopyConstructible 它必须可以复制这个类型
  Non-throwing destructor 就象所有析构函数应该的那样!
  Assignable 为了保证强异常安全(不符合可赋值要求的类型也可以用于  any, 但没有强
异常安全的保证)

 

Any用法

Any库定义在名字空间  boost 内。你要用类  any 来保存值,用模板函数  any_cast 来取回存放
的值。为了使用  any, 要包含头文件  "boost/any.hpp". 创建一个可以存放任意值的实例是很容
易的。
boost::any a;

把任意类型的值赋给any也很方便

boost::any a=string("hello");

boost::any a=10;

boost::any a=54.6;

从any中取出值要麻烦些,不过这保证了安全性,any不允许在不知道类型的情况下取出值,但提供了获取类型信息的接口。

int b;

if(typeid(string)==a.type())

{

b=any_cast<int>(a);  // 有点像stl中的类型转换方式

}

如果直接 b=a的话将会抛出一个异常bad_any_cast。

代码示例

   1:  
   2:  
   3: #include <boost/any.hpp>
   4: #include <iostream>
   5: #include <vector>
   7: #include <string> 
   8:  
   9: using namespace std;
  10: using namespace boost; 
  11:  
  12: void print(boost::any& arr)
  13: {
  14:  
  15: if(typeid(string)==arr.type())
  16:  
  17: {
  18:  
  19: cout<<any_cast<string>(arr)<<endl;
  20:  
  21: }
  22:  if(typeid(int)==arr.type())
  23:  
  24: {
  25:  
  26: cout<<any_cast<int>(arr)<<endl;
  27:  
  28: }
  29:  if(typeid(char)==arr.type())
  30:  
  31: {
  32:  
  33: cout<<any_cast<char>(arr)<<endl;
  34:  
  35: }
  36:  if(typeid(double)==arr.type())
  37:  
  38: {
  39:  
  40: cout<<any_cast<double>(arr)<<endl;
  41:  
  42: }
  43: } 
  44:  
  45: int main(int argc, char* argv[])
  46: {
  47:  
  48: vector<boost::any> any_arr;
  49:  
  50: any_arr.push_back(string("hello"));
  51:  
  52: any_arr.push_back(10);
  53:  
  54: any_arr.push_back('a');
  55:  
  56: any_arr.push_back(56.0);
  57:  for(int 
  58: i=0;i<any_arr.size();i++)
  59:  
  60: {
  61:  
  62: print(any_arr[i]);
  63:  }
  64:  return 
  65: 0;
  66: }

posted on 2011-06-22 18:37 Nobooy 阅读(649) 评论(0)  编辑 收藏 引用 所属分类: STL/Boost


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2011年6月>
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

统计

常用链接

留言簿

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜