Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

c++ - Unpacking arguments from tuples

So I'm trying to figure out how this works: C++11: I can go from multiple args to tuple, but can I go from tuple to multiple args?

The piece of black magic I do not understand is this code fragment:

f(std::get<N>(std::forward<Tuple>(t))...)

it's the expression inside f that I don't understand.

I understand that the expression somehow unpacks/expands what's inside t into a list of arguments. But could someone care to explain how this is done? When I look at the definition of std::get (http://en.cppreference.com/w/cpp/utility/tuple/get), I don't see how N fits in...? As far as I can tell, N is a sequence of integers.

Based on what I can observe, I'm assuming that expressions in the form E<X>... where X is the sequence of types X1. X2, ... Xn, the expression will be expanded as E<X1>, E<X2> ... E<Xn>. Is this how it works?

Edit: In this case N is not a sequence of types, but integers. But I'm guessing this language construct applies to both types and values.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think that @Xeo's comment summed it up well. From 14.5.3 of the C++11 standard:

A pack expansion consists of a pattern and an ellipsis, the instantiation of which produces zero or more instantiations of the pattern in a list.

In your case, by the time you finish with the recursive template instantiation and end up in the partial specialization, you have

f(std::get<N>(std::forward<Tuple>(t))...);

...where N is parameter pack of four ints (0, 1, 2, and 3). From the standardese above, the pattern here is

std::get<N>(std::forward<Tuple>(t))

The application of the ... ellipsis to the above pattern causes it to be expanded into four instantiations in list form, i.e.

f(std::get<0>(t), std::get<1>(t), std::get<2>(t), std::get<3>(t));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...