简体   繁体   中英

In C++, can you have a function that modifies a tuple of variable length?

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 ?

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.

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.

Take a look at section 6.1.3.4 of TR1, http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1836.pdf

get is defined for both const and non-const qualified tuples and returns the appropriate reference type. If you change your function declaration to the following:

template 
void fun(typename std::tuple& my_tuple) {
    //Put things into the tuple
}

Then the argument to your function is a non-const tuple and get will allow you to make the necessary assignments once you've written the iteration using the information provided in previous responses.

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.

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

How do I expand a tuple into variadic template function's arguments?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM