Tuple to parameter pack

后端 未结 2 563
情深已故
情深已故 2020-12-24 08:48

This below code from user Faheem Mitha, is based on user Johannes Schaub - litb\'s answer in this SO. This code perfectly does what I seek, which is conversion of a tu

2条回答
  •  天命终不由人
    2020-12-24 09:08

    Let's look at what happens here:

    template struct gens : gens { };
    
    template struct gens<0, S...>{ typedef seq type; };
    

    The first one is a generic template, the second one is a specialization that applies when the first template parameter is 0.

    Now, take a piece of paper and pencil, and write down how

     gens<3>
    

    gets defined by the above template. If your answer was:

     struct gens<3> : public gens<2, 2>
    

    then you were right. That's how the first template gets expanded when N is "3", and ...S is empty. gens, therefore, becomes gens<2, 2>.

    Now, let's keep going, and see how gens<2, 2> gets defined:

     struct gens<2, 2> : public gens<1, 1, 2>
    

    Here, in the template expansion, N is 2, and ...S is "2". Now, let's take the next step, and see how gens<1, 1, 2> is defined:

     struct gens<1, 1, 2> : public gens<0, 0, 1, 2>
    

    Ok, now how does gens<0, 0, 1, 2> gets defined? It can now be defined by the specialization:

     template struct gens<0, S...>{ typedef seq type; };
    

    So, what happens with struct gens<0, 0, 1, 2> here? Well, in the specialization, "S..." becomes "0, 1, 2", so this becomes, in a manner of speaking:

     struct gens<0, 0, 1, 2> {
    
       typedef seq<0, 1, 2> type;
    
     }
    

    Now, keep in mind that all of these publicly inherit from each other, "elephant-style", so:

     gens<3>::type
    

    ends up being a typedef declaration for

     struct seq<0, 1, 2>
    

    And this is used, by the code that follows to convert the tuple into a parameter pack, using another template:

    double delayed_dispatch()
    {
        return callFunc(typename gens::type()); // Item #1
    }
    

    ...Args are the tuple parameters. So, if there are three elements in the tuple, sizeof(...Args) is 3, and as I've explained above, gens::type() becomes gens<3>::type(), a.k.a. seq<0, 1, 2>().

    So, now:

    template
    double callFunc(seq)
    {
        return func(std::get(params) ...);
    }
    

    The S... part becomes "0, 1, 2", so the

    std::get(params)...
    

    Becomes a parameter pack that gets expanded to:

    std::get<0>(params), std::get<1>(params), std::get<2>(params),
    

    And that's how a tuple becomes a parameter pack.

提交回复
热议问题