Iterator for boost::variant

六眼飞鱼酱① 提交于 2019-12-05 12:03:07

Well of course there is. Dereferencing the iterators will naturally yield a boost::variant<...> reference or const-reference.

However it does mean that the rest of code should be variant-aware. And notably use the boost::static_visitor to execute operations on the variants.

EDIT:

Easy!

struct Printer: boost::static_visitor<>
{
  template <class T>
  void operator()(T const& t) const { std::cout << t << std::endl; }
};

std::for_each(bag.begin(), bag.end(), boost::apply_visitor(Printer());

Note how writing a visitor automatically yields a predicate for STL algorithms, miam!

Now, for the issue of the return value:

class WithReturn: boost::static_visitor<>
{
public:
  WithReturn(int& result): mResult(result) {}

  void operator()(Foo const& f) const { mResult += f.suprise(); }
  void operator()(Bar const& b) const { mResult += b.another(); }

private:
  int& mResult;
};


int result;
std::for_each(bag.begin(), bag.end(), boost::apply_visitor(WithReturn(result)));

EDIT 2:

It's easy, but indeed need a bit of coaching :)

First, we remark there are 2 different operations: != and operate

 struct PropertyCompare: boost::static_visitor<bool>
 {
   template <class T, class U>
   bool operator()(T const& lhs, U const& rhs)
   {
     return lhs.property() == rhs.property();
   }
 };

 struct Operate: boost::static_visitor<result_type>
 {
   result_type operator()(Foo const& lhs, Foo const& rhs);
   result_type operator()(Foo const& lhs, Bar const& rhs);
   result_type operator()(Bar const& lhs, Bar const& rhs);
   result_type operator()(Bar const& lhs, Foo const& rhs);
 };

for(it=list.begin(); it!=list.end();++it) {
  for(it_2=list.begin(); it_2!=list.end();++it_2) {

    if( !boost::apply_visitor(PropertyCompare(), *it, *it_2) ) {

      result = boost::apply_visitor(Operate(), *it, *it_2));

    }

  }
}

For each is not that good here, because of this if. It would work if you could somehow factor the if in operate though.

Also note that I pass not iterators but references.

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