Iterating over Boost fusion::vector

前端 未结 4 1631
萌比男神i
萌比男神i 2021-01-16 05:33

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

typedef typename fusion::result_of::begin::type t_iter;
  std::cout << distance(begi         


        
相关标签:
4条回答
  • 2021-01-16 06:01

    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);
                                             ^^^^^
    
    0 讨论(0)
  • 2021-01-16 06:22

    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() );
    
    0 讨论(0)
  • 2021-01-16 06:22

    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

    0 讨论(0)
  • 2021-01-16 06:22

    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.

    0 讨论(0)
提交回复
热议问题