C++ boost::variant的迭代器

C++ boost::variant的迭代器,c++,boost,variant,boost-variant,C++,Boost,Variant,Boost Variant,好了 我正在尝试将现有代码改编为boost::variant。其思想是对异构向量使用boost::variant。问题是代码的其余部分使用迭代器访问向量的元素。有没有办法将boost::variant与迭代器一起使用 我试过了 typedef boost::variant<Foo, Bar> Variant; std::vector<Variant> bag; std::vector<Variant>::iterator it; for(it= bag

好了

我正在尝试将现有代码改编为boost::variant。其思想是对异构向量使用boost::variant。问题是代码的其余部分使用迭代器访问向量的元素。有没有办法将boost::variant与迭代器一起使用

我试过了

 typedef boost::variant<Foo, Bar> Variant;
 std::vector<Variant> bag;
 std::vector<Variant>::iterator it;
 for(it= bag.begin(); it != bag.end(); ++it){

 cout<<(*it)<<endl;
 }

谢谢

当然有。取消对迭代器的引用自然会产生一个
boost::variant
引用或const引用

然而,这确实意味着代码的其余部分应该是变量感知的。特别是使用
boost::static_visitor
对变量执行操作

编辑

轻松点

因为这
if
,这里的For-each不是很好。但是,如果您能够在
操作中以某种方式将
if
因素考虑在内,那么这将是可行的


还要注意,我传递的不是迭代器,而是引用。

boost::static\u访问者可以很好地对元素进行操作,但在类必须返回一些数据时不起作用。我曾尝试对boost::ptr_vector使用迭代器,但类似的方法不起作用:typedef boost::variant;病媒袋;std::vector::it迭代器;对于(it=bag.begin();it!=bag.end();++it){coutEdited该条目以说明其用法。非常感谢。仍在尝试在不做太多更改的情况下使该概念适应我的现有代码。请在上面进行新编辑。
for(it=list.begin(); it!=list.end();++it) {
  for(it_2=list.begin(); it_2!=list.end();++it_2) {

     if(it->property() != it_2->property()) {

        result = operate(it,it_2);

       }
    }

}
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());
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)));
 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));

    }

  }
}