Iterating over Boost fusion::vector

空扰寡人 提交于 2019-12-02 06:24:55
K-ballo

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

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

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);
                                         ^^^^^

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.

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