tags:

views:

590

answers:

5

In C++0x I would like to write a function like this:

template <typename... Types>
void fun(typename std::tuple<Types...> my_tuple) {
    //Put things into the tuple
}

I first tried to use a for loop on int i and then do:

get<i>(my_tuple);

And then store some value in the result. However, get only works on constexpr.

If I could get the variables out of the tuple and pass them to a variadic templated function I could recurse through the arguments very easily, but I have no idea how to get the variables out of the tuple without get. Any ideas on how to do that? Or does anyone have another way of modifying this tuple?

+4  A: 

Since the "i" in

get<i>(tup)

needs to be a compile-time constant, template instantiation is used to "iterate" (actually recurse) through the values. Boost tuples have the "length" and "element" meta-functions that can be helpful here -- I assume C++0x has these too.

Adam Mitz
Thanks! My code now looks like this: template<int nPos, typename... Types> void fun(typename std::tuple<Types...> my_tuple) { get<nPos>(my_tuple); fun<nPos+1>(my_tuple); }
+3  A: 

Boost.Fusion is worth a look. It can 'iterate' over std::pair, boost::tuple, some other containers and its own tuple types, although I don't think it supports std::tuple yet.

Daniel James
A: 
Timmie Smith
A: 

AFAICT, C++ tuples basically need to be handled with recursion; there don't seem to be any real ways of packing/unpacking tuples except using the typesystem's only variadic template handling.

DrPizza
A: 

Have a look at my answer here for an example of template recursion to unwind tuple arguments to a function call.

http://stackoverflow.com/questions/687490/c0x-how-do-i-expand-a-tuple-into-variadic-template-function-arguments

David