boost 的 any
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.
[...] boost.any 的东西。boost.any 是为了提供 heterogeneous container 给出的一种解决思路,我们知道 STL [...]
C++ 的 idioms(二) « demonstrate 的 blog
2012/02/19 at 5:35 AM