How do I strip a tuple<> back into a variadic template list of types?

后端 未结 5 2346
死守一世寂寞
死守一世寂寞 2020-12-15 07:29

Is there a way to strip a std::tuple in order to get it back to T...?

Example

Suppose

5条回答
  •  不知归路
    2020-12-15 08:15

    The goal here is to be able to copy a parameter pack from an instance of a template, to another template. I didn't restrict it to tuple, because... why restrict it to tuple?

    templateclass Target, typename Src>
    struct copy_pack_types;
    
    templateclass Target, templateclass Src, typename... Ts>
    struct copy_pack_types< Target, Src > {
      typedef Target type;
    };
    
    templateclass Target, typename Src>
    using CopyPackTypes = typename copy_pack_types::type;
    
    #include 
    #include 
    template struct vct;
    template struct vct2;
    using U = std::tuple;
    using X = vct;
    using Y = CopyPackTypes< vct, U >;            // should be same as X
    using Z = CopyPackTypes< vct2, U >;            // should be different from X
    
    #include 
    #include 
    int main() {
      std::cout << std::is_same< X, Y >::value << "\n";
      std::cout << std::is_same< Z, Y >::value << "\n";
      std::cout << std::is_same< Z, vct2 >::value << "\n";
    }
    

    output is "1 0 1" as expected.

    The CopyPackTypes takes a target template, and a source type that was constructed from a parameter pack as its only argument. It then copies the parameter pack to the target template.

    One standard technique is to carry parameter packs around is to create an otherwise no use type like:

    template
    struct types {};
    

    which only exists as a placeholder for a list of types. You can then pass a few of these to another template, and each pack doesn't "step on" each other. When you need to apply it to a target template, you use something like the above "CopyPackTypes" to apply it.

    Similar techniques are used for packs of indexes:

    template
    struct seq {};
    

    otherwise useless types that are "black slates" to carry clumps of parameters around.

提交回复
热议问题