Search code examples
c++boostiteratorboost-fusion

Iterating over Boost fusion::vector


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!


Solution

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