C++ 将类型参数包转换为索引参数包

C++ Convert a parameter pack of types to parameter pack of indices

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

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

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

例如,foo<int,float,double>()应该调用bar<0, 1, 2>()

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

在 C++14 中,您可以使用 <utility> header 中的 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.