添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
boost :: any t ;
t = 4;
std :: cout << boost :: any_cast < int >( t ) << std :: endl ;
t = std :: string ( "hello world!" );
std :: cout << boost :: any_cast < std :: string >( t ) << std :: endl ;
定义any类型后,既可以赋int类型,也可以赋std::string类型,通过boost的any_cast进行显式转换,这个转换发生在运行期,因此转型可能失败,失败会抛出 boost :: bad_any_cast异常,如果传入的是any*类型则,可以通过转型后返回指针是否为空判断转型是否成功.
bool is_int ( const boost :: any & operand )
/* 利用 typeid 进行类型判定 */
return operand . type () == typeid ( int );
bool is_char_ptr ( const boost :: any & operand )
/* 捕获异常判断转型 */
boost :: any_cast < const char *>( operand );
return true ;
catch ( const boost :: bad_any_cast &)
return false ;
bool is_string ( const boost :: any & operand )
/* 判定返回指针是否为空 */
return boost :: any_cast < std :: string >(& operand );
同样any可以作为容器的元素如下:
std :: vector < boost :: any > v ;
v . push_back (4);
v . push_back ( std :: string ( "123456" ));
v . push_back ( std :: string ( "hello world!" ));
std :: cout << std :: count_if ( v . begin (), v . end (), is_string );