C++ 与 Boost (Any,Variant)

1. Boost.Any

boost::any 并不能真的存储任意类型的值; Boost.Any 需要一些特定的前提条件才能工作。 任何想要存储在 boost::any 中的值,都必须是可拷贝构造的。 因此,想要在 boost::any 存储一个字符串类型的值, 就必须要用到 std::string , 就像在下面那个例子中做的一样。

#include <boost/any.hpp> 
#include <string> 

int main() 
{ 
  boost::any a = 1; 
  a = 3.14; 
  a = true; 
  a = std::string("Hello, world!"); 
} 

用 boost::any_cast 来定义一个指向 boost::any 中内容的指针,想要检查 boost::any 是否为空, 你可以使用 empty() 函数。 想要确定其中具体的类型信息, 你可以使用 type() 函数

boost::any a = 1; 
if (!a.empty()) 
{ 
   int *i = boost::any_cast<int>(&a); 
   std::cout << *i << std::endl; 
}

2. Boost.Variant

Boost.Variant 只能被视为固定数量的类型, 可以使用独立的 boost::get() 函数获取其中的数据。

#include <boost/variant.hpp> 
#include <string> 
std::vector<boost::any> vector; 
struct output : 
   public boost::static_visitor<> 
{ 
  void operator()(double &d) const 
  { 
    vector.push_back(d); 
  } 

  void operator()(char &c) const 
  { 
    vector.push_back(c); 
  } 

  void operator()(std::string &s) const 
  { 
    vector.push_back(s); 
  } 
}; 

int main() 
{ 
  boost::variant<double, char, std::string> v; 
  v = 3.14; 
  v = 'A'; 
  v = "Hello, world!";  
  std::cout << boost::get<double>(v) << std::endl;
  std::cout << boost::get<char>(v) << std::endl;
  std::cout << boost::get<std::string>(v) << std::endl;
  
  boost::apply_visitor(output(), v); 
  boost::apply_visitor(output(), v); 
  boost::apply_visitor(output(), v); 
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值