boost 库 applyvisitor使用

本文介绍了Boost.Variant库,它用于存储和操作不同类型对象,支持类型安全访问。还探讨了Variant库对程序的改进,以及variant的几种访问方法,包括使用boost::get、RTTI、访问者模式和模板函数,并分析了各方法的优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

boost::variant and boost::apply_visitor
2017年11月02日 15:30:52 秋云 阅读数:448

转自:http://www.jb51.net/article/95814.htm

Boost.Variant

Variant库包含一个不同于union的泛型类,用于在存储和操作来自于不同类型的对象。这个库的一个特点是支持类型安全的访问,减少了不同数据类型的类型转换代码的共同问题。

Variant 库如何改进你的程序?

 •对用户指定的多种类型的进行类型安全的存储和取回

 •在标准库容器中存储不同类型的方法

 •变量访问的编译期检查

 •高效的、基于栈的变量存储

Variant 库关注的是对一组限定类型的类型安全存储及取回,即非无类的联合。Boost.Variant 库与 Boost.Any 有许多共同之外,但在功能上也有不同的考虑。在每天的编程中通常都会需要用到非无类的联合(不同的类型)。保持类型安全的一个典型方法是使用抽象基类,但这不总是可以做到的;即使可以做得,堆分配和虚拟函数的代价也可能太高。你也可以尝试用不安全的无类类型,如 void* (它会导致不幸),或者是类型安全得无限制的可变类型,如 Boost.Any. 这里我们将看到 Boost.Variant,它支持限定的可变类型,即元素来自于一组支持的类型。

下面将浅谈variant的几种访问方法,一起来学习学习吧。

使用boost::get

boost::variant<int, std::string> v;
v = “Hello world”;
std::cout << boost::getstd::string(v) << std::endl;
使用boost::get来访问,需要给出原始类型,并且这样做不安全,若类型错误,程序将会抛出异常。

使用RTTI

void var_print(boost::variant<int, std::string>& v)
{
if (v.type() == typeid(int))
{
std::cout << get(v) << std::endl;
}
else if (v.type() == typeid(std::string))
{
std::cout << getstd::string(v) << std::endl;
}
// Else do nothing
}
int main()
{
boost::variant<int, std::string> v;
v = “Hello world”;
var_print(v);
return 0;
}
使用RTTI技术可以避免类型访问错误而程序异常的情况,但是这样做有点不优雅,每增加一个类型,都需要修改if-else结构,并且使用RTTI会对程序性能有一定影响。

使用访问者模式

class var_visitor : public boost::static_visitor
{
public:
void operator()(int& i) const
{
std::cout << i << std::endl;
}
void operator()(std::string& str) const
{
std::cout << str << std::endl;
}
};
int main()
{
boost::variant<int, std::string> v;
v = “Hello world”;
boost::apply_visitor(var_visitor(), v);
return 0;
}
使用该模式,需要定义一个类并继承于boost::static_visitor,在类里面需要重载()操作符,通过boost::apply_visitor来访问原始类型的值,这样做还是有些繁琐,每增加一个类型,都需要在var_visitor里面增加一个函数,但比使用RTTI里面的修改if-else结构好得多,因为使用访问者模式至少是遵循开放-封闭原则的,即对写开放,对修改封闭。

使用模板函数

class var_visitor : public boost::static_visitor
{
public:
template
void operator()(T& i) const
{
std::cout << i << std::endl;
}
};
int main()
{
boost::variant<int, std::string> v;
v = “Hello world”;
boost::apply_visitor(var_visitor(), v);
return 0;
}
将operator()改成了模板函数的好处就是不用关心variant支持多少类型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值