问题
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);
...
}
}
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?
回答1:
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.
来源:https://stackoverflow.com/questions/54032817/boostget-vs-boostapply-visitor-when-fetching-values-from-a-variant