Search code examples
c++templatesvariadic-templatesconstexprc++14

C++1y/C++14: Converting static constexpr array to non-type template parameter pack?


Suppose I have a constexpr array (of known bound) of static storage duration:

constexpr T input[] = /* ... */;

And I have an output class template that needs a pack:

template<T...> struct output_template;

I want to instantiate output_template like:

using output = output_template<input[0], input[1], ..., input[n-1]>;

One way to do this is:

template<size_t n, const T (&a)[n]>
struct make_output_template
{
    template<size_t... i> static constexpr
    output_template<a[i]...> f(std::index_sequence<i...>)
    { return {}; };

    using type = decltype(f(std::make_index_sequence<n>()));
};

using output = make_output_template<std::extent_v<decltype(input)>, input>::type;

Is there a cleaner or simpler solution I am missing?


Solution

  • Maybe you consider this to be cleaner:

    template< const T* a, typename >
    struct make_output_template;
    
    template< const T* a, std::size_t... i >
    struct make_output_template< a, std::index_sequence< i... > >
    {
        using type = output_template< a[ i ]... >;
    };
    

    with

    using output = make_output_template<
        input,
        std::make_index_sequence< std::extent_v< decltype( input ) > >
    >::type;