C++ 1y/C++ 14:将静态constexpr数组转换为非类型模板参数包?

And*_*zos 5 c++ templates variadic-templates constexpr c++14

假设我有一个静态存储持续时间的constexpr数组(已知绑定):

constexpr T input[] = /* ... */;
Run Code Online (Sandbox Code Playgroud)

我有一个需要包的输出类模板:

template<T...> struct output_template;
Run Code Online (Sandbox Code Playgroud)

我想实例化output_template如下:

using output = output_template<input[0], input[1], ..., input[n-1]>;
Run Code Online (Sandbox Code Playgroud)

一种方法是:

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;
Run Code Online (Sandbox Code Playgroud)

我缺少更清洁或更简单的解决方案吗?

Dan*_*rey 8

也许你认为这更清洁:

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 ]... >;
};
Run Code Online (Sandbox Code Playgroud)

using output = make_output_template<
    input,
    std::make_index_sequence< std::extent_v< decltype( input ) > >
>::type;
Run Code Online (Sandbox Code Playgroud)

  • @ Manu343726是的,你是对的,一旦你用`std :: extend <...> :: value`替换`std :: extend_v <...>`你就需要它C++ 11 `std :: make_index_sequence`的版本. (2认同)