Iterating over Boost fusion::vector

半城伤御伤魂 提交于 2019-12-02 11:26:15

问题


I'm trying to iterate over a boost::fusion vector using:

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

The distance cout statement gives me a finite length (2), however the loop seems to run indefinitely.

Any advice much appreciated!


回答1:


You can't just iterate a Fusion vector like that, the type for each iterator may be different than the previous one (and usually is). I guess that's why you don't have it = next(it) in your code, it would give a compilation error.

You could use boost::fusion::for_each for this, together with a function object that prints each element to the standard output:

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

...

boost::fusion::for_each( t, print() );



回答2:


fusion is a wonderful library, and you should now that it is really different from what you use in every day C++ programs in multiple ways, it merge the power of compile time meta programming with runtime, for that you should now that there is no type that can handle all items in a fusion container. What this means? it means that result_of::begin<T>::type is not always a match of next(it) so you can't use fusion iterators in a for like that.

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




回答3:


next doesn't actually advance the iterator, it just returns the next one.

This can be seen in the docs, as the function next takes a constant argument, meaning it can't possibly actually modify the iterator:

template<
    typename I
    >
typename result_of::next<I>::type next(I const& i);
                                         ^^^^^



回答4:


The problem is that inside the loop you are dereferencing your iterator. When you apply next on it, it means nothing and that's why your loop runs forever.



来源:https://stackoverflow.com/questions/13094535/iterating-over-boost-fusionvector

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