demonstrate 的 blog

daily blog

boost 的 any

with one comment

any 可以为异类数据提供统一的接口,这样就能放在 type 一样的容器中了。

#include <vector>
#include <string>
#include <iostream>

#include <boost/any.hpp>
#include <boost/assign/std/vector.hpp>

struct foo {
  foo() { std::cout << "default" << std::endl ; }
  foo(const foo& a) { std::cout << "copy" << std::endl ; }
} ;

int
main(int argc, char* argv[] ) {
  using namespace boost::assign ;

  std::vector<boost::any> v ;
  boost::any a = 5 ;
  boost::any b = std::string("hello world") ;
  boost::any c = 1.4 ;
  boost::any d = foo() ;
  v += a,b,c,d ;

  std::cout << v[0].empty() << std::endl
            << (v[0].type() == typeid(int)) << std::endl
            << boost::any_cast<int>( v[0] ) << std::endl ;

  return 0 ;
}

运行结果如下

default
copy
copy
copy
0
1
5

不难发现 any 应该是将数据复制了一份,使用的指针,并记录了类型,在使用 boost::any_cast 的时候会进行类型检查,失败后会抛出 bad_any_cast 异常。这里三个 copy 分别在给 boost::any 赋值,逗号 operator 和 += 插入到容器时调用的。

——————
Man’s history is waiting in patience for the triumph of the insulted man.

Written by zt

2010/12/10 at 12:10 AM

Posted in c/c++

Tagged with ,

One Response

Subscribe to comments with RSS.

  1. [...] boost.any 的东西。boost.any 是为了提供 heterogeneous container 给出的一种解决思路,我们知道 STL [...]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.