boost::get vs boost::apply_visitor when fetching values from a variant

这一生的挚爱 提交于 2019-12-11 08:57:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!