How do I “expand” a compile-time std::array into a parameter pack?

后端 未结 2 668
隐瞒了意图╮
隐瞒了意图╮ 2021-01-14 09:37

I\'d like to use partial template specialization in order to \'break down\' an array (which is created at compile time) into a parameter pack composed of its values (to inte

2条回答
  •  北海茫月
    2021-01-14 09:47

    Inspired by @dfri 's answer, I transformed her / his solution to a version which can omit functions, but instead uses only one struct using partial template specialization for the std::integer_sequence which might also be interesting to others:

    template  typename Consumer,
              typename IS = decltype(std::make_index_sequence())> struct Generator;
    
    template  typename Consumer, std::size_t... I>
    struct Generator> {
      using type = Consumer;
    };
    

    Full example with usage:

    #include 
    
    /// Structure which wants to consume the array via a parameter pack.
    template  struct ConsumerStruct {
      constexpr auto operator()() const { return std::array{s...}; }
    };
    
    /// Solution
    template  typename Consumer,
              typename IS = decltype(std::make_index_sequence())> struct Generator;
    
    template  typename Consumer, std::size_t... I>
    struct Generator> {
      using type = Consumer;
    };
    
    /// Helper typename
    template  typename Consumer>
    using Generator_t = typename Generator::type;
    
    // Usage
    int main() {
      constexpr auto tup = std::array{{1, 5, 42}};
      constexpr Generator_t tt;
      static_assert(tt() == tup);
      return 0;
    }
    

提交回复
热议问题