【问题标题】:C++1y/C++14: Converting static constexpr array to non-type template parameter pack?C++1y/C++14:将静态 constexpr 数组转换为非类型模板参数包?
【发布时间】:2014-07-03 18:05:23
【问题描述】:

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

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

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

template<T...> struct output_template;

我想实例化output_template 喜欢:

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

一种方法是:

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;

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

【问题讨论】:

  • 您在寻找什么?更简单的接口或实现?
  • the indices trick 在这里有用吗?你没有模板索引参数可以在这里使用,就像你使用元组一样,但是......
  • using output = decltype(deduce(input))::unpack&lt;input&gt;;?不过,清洁度并不高。
  • a 的@dyp 链接似乎是一个障碍(即使在适当的地方有更多 constexpr):coliru.stacked-crooked.com/a/2c196c6f2a82cbfb
  • 这似乎是proposal n3601 的另一个潜在应用,据我所知,这将允许using output = foo&lt;input&gt;;

标签: c++ templates variadic-templates constexpr c++14


【解决方案1】:

也许你认为这样更干净:

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 ]... >;
};

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

【讨论】:

  • 我确实知道,先生,谢谢。我猜我见过的所有 index_sequence 的例子都使用了函数参数的推导,所以我没有想到在类上使用部分特化。
  • 没有任何语言特定的功能可以阻止我使用 C++11 进行尝试,不是吗?
  • @Manu343726 是的,你是对的,一旦你将std::extend_v&lt;...&gt; 替换为std::extend&lt;...&gt;::value 并且你推出了自己的std::make_index_sequence 版本,它就需要C++11。
猜你喜欢
  • 2017-09-17
  • 1970-01-01
  • 1970-01-01
  • 2016-03-01
  • 2016-09-15
  • 1970-01-01
  • 2013-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多