从变量获取值时,boost :: get与boost :: apply_visitor [英] boost::get vs boost::apply_visitor when fetching values from a variant
问题描述
我们在生产代码中广泛使用了boost :: variant的集合。
我们从此集合中提取值的方式是
We are using collections of boost::variant extensively in our production code. The way we extract the values from this collection is
for (auto & var : vars)
{
switch (var.which())
{
case 1 :
AVal = boost::get<A>(var);
break;
case 2 :
BVal = boost::get<B> (var);
...
}
}
了解有关变体的更多信息我可以看到另一种替代方法是
Reading more about variants I can see that a different alternative would be
for (auto & var : vars)
{
switch (var.which())
{
case 1 :
AVal = boost::apply_visitor(AVisitor, var);
break;
case 2 :
BVal = boost::apply_visitor(BVisitor, var);
...
}
}
忽略以下事实apply_visitor提供编译时类型安全值访问,并且功能更强大,我是否应该期望上述两种方法在运行时性能方面有任何差异?
Ignoring the fact that apply_visitor provides compile time type safe value visitation and is more powerful, should I expect any difference in terms of run time performance for either of the above approaches?
推荐答案
boost :: variant
只是与您提供的最大数据类型对齐的内存块,而整数则指定当前使用的是哪种类型。还有许多允许访问逻辑的编译时宏。
boost::variant
is just a block of memory that is aligned to biggest data type you provide, and an integer specifying which of these types is currently use. And a lot of compile-time macros allowing for visitation logic.
丢弃一次或两次运行时检查,以确保获取正确的类型,访问该内存位置的其他费用(重新解释为所需的类型)应该没有其他费用。
Discarding one or two run-time checks making sure right type is getting grabbed, there should be no other cost for accessing that memory location, reinterpreted as the desired type.
这篇关于从变量获取值时,boost :: get与boost :: apply_visitor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!