1

我正在尝试使用以下方法迭代 boost::fusion 向量:

typedef typename fusion::result_of::begin<T>::type t_iter;
  std::cout << distance(begin(t), end(t)) << std::endl;
  for(t_iter it = begin(t); it != end(t); next(it)){
    std::cout<<deref(it)<<std::endl;
  }

distance cout 语句给了我一个有限的长度 (2),但是循环似乎无限期地运行。

非常感谢任何建议!

4

4 回答 4

4

你不能像这样迭代一个Fusion向量,每个迭代器的类型可能与前一个不同(通常是)。我想这就是你的代码中没有的原因it = next(it),它会产生编译错误。

您可以将boost::fusion::for_each其与将每个元素打印到标准输出的函数对象一起使用:

struct print
{
    template< typename T >
    void operator()( T& v ) const
    {
        std::cout << v;
    }
};

...

boost::fusion::for_each( t, print() );
于 2012-10-26T21:20:00.557 回答
2

fusion是一个很棒的库,你现在应该知道它在很多方面与你在日常 C++ 程序中使用的不同,它结合了编译时元编程的力量和运行时,因为你现在应该没有那种类型可以处理一个fusion容器中的所有物品。这意味着什么?这意味着这result_of::begin<T>::type并不总是匹配的,next(it)因此您不能像那样使用fusion迭代器for

The obvious problem in your code is that you ignore return value of next and it will cause your code to run forever but you can't use it in it = next(it), since their type may vary!!

So what you should do?? You should use boost::fusion::for_each for that purpose

于 2012-10-26T21:25:33.177 回答
1

next实际上并不推进迭代器,它只是返回下一个。

这可以在文档中看到,因为该函数next接受一个常量参数,这意味着它实际上不可能修改迭代器:

template<
    typename I
    >
typename result_of::next<I>::type next(I const& i);
                                         ^^^^^
于 2012-10-26T21:20:38.840 回答
0

问题是在循环内你正在取消引用你的迭代器。当你申请next它时,它没有任何意义,这就是你的循环永远运行的原因。

于 2012-10-26T21:17:40.340 回答