Search code examples
c++c++11iterationtemplate-meta-programmingstdtuple

How can you iterate over the elements of an std::tuple?


How can I iterate over a tuple (using C++11)? I tried the following:

for(int i=0; i<std::tuple_size<T...>::value; ++i) 
  std::get<i>(my_tuple).do_sth();

but this doesn't work:

Error 1: sorry, unimplemented: cannot expand ‘Listener ...’ into a fixed-length argument list.
Error 2: i cannot appear in a constant expression.

So, how do I correctly iterate over the elements of a tuple?


Solution

  • Boost.Fusion is a possibility:

    Untested example:

    struct DoSomething
    {
        template<typename T>
        void operator()(T& t) const
        {
            t.do_sth();
        }
    };
    
    tuple<....> t = ...;
    boost::fusion::for_each(t, DoSomething());