【问题标题】:C++ Convert a parameter pack of types to parameter pack of indicesC++ 将类型参数包转换为索引参数包
【发布时间】:2015-06-25 15:04:22
【问题描述】:

有没有办法将类型参数包转换为从0sizeof...(Types) 的整数参数包?更具体地说,我正在尝试这样做:

template <size_t... I>
  void bar();

template <typename... Types>
  void foo() {
    bar<WHAT_GOES_HERE<Types>...>();
  }

例如,foo&lt;int,float,double&gt;() 应该调用bar&lt;0, 1, 2&gt;()

在我的用例中,参数包Types 可能包含多次相同的类型,因此我无法搜索包来计算给定类型的索引。

【问题讨论】:

  • 真正的问题是什么?我相信我们可以提供更好的建议。
  • bar&lt;0, 1, 2&gt;()bar&lt;3&gt;() 有什么好处?
  • 如果我有template &lt;typename... Args&gt; void g(Args&amp;&amp;...);template &lt;size_t I&gt; auto h();。我希望能够从提供给foo() 的参数包中执行g(h&lt;I&gt;()...);。 TartanLlama 的解决方案有效。我正在使用这些模板技巧来实现“数组结构”容器类型的复制构造函数,该容器类型本身使用可变参数模板来定义类型。

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


【解决方案1】:

在 C++14 中,您可以使用 &lt;utility&gt; 标头中的 std::index_sequence_for 以及标记调度。这被称为索引技巧

template <std::size_t... I>
void bar(std::index_sequence<I...>);

template <typename... Types>
void foo() {
    bar(std::index_sequence_for<Types...>{});
}

如果你仅限于C++11,可以在网上找到很多上面的实现,比如this one

【讨论】:

  • @RyanHaining 至少有六种 integer_sequence 和朋友在 SO 上的实现。
  • @T.C.我敢肯定,但在 c++11 中它不会出现在 &lt;utility&gt; 中,所以答案具有误导性。在这里链接到一个实现会很有用
  • C++14 对我来说没问题。我已经更改了问题的标签。无论如何,正如其他人所说,如果不可用,可以重新实现整数序列。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-31
  • 1970-01-01
  • 2016-04-29
  • 1970-01-01
  • 2021-05-17
  • 1970-01-01
相关资源
最近更新 更多