generically convert from boost::variant<T> to type

走远了吗. 提交于 2019-12-03 14:20:30

Actually looking at your code some more, here is a different option - again based on using visitor..

struct add_node_visitor : boost::static_visitor<>
{
  add_node_visitor(<type of modvalue> & node, <type of key> & key) : _node(node), _key(key) {}

  template <typename _Item>
  void operator()(_Item const& item)
  {
    node->AddNodeAttribute(_key, item);
  }  

  <type of modvalue> & _node;
  <type of key> & _key;
}

to use:

boost::apply_visitor (add_node_visitor(modmodvalue, key), mystruct.variant);

As long as your AddNodeAttribute has overloads for all types, the above should work...

When I was using boost::variant I would always access the contained data using visitor technique. In my opinion this is a very elegant way. It does not rely on switch-logic, which is really a sign of bad design. See the documentation.

Good luck!

... What does AddNodeAttribute do? Basically the same thing for each type, right? If you have a container of node attributes somewhere, then it basically needs to be a container of the variant type, right?

... So why not just rewrite AddNodeAttribute to be a single function accepting a variant?

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