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

↘锁芯ラ 提交于 2019-12-21 12:42:56

问题


Is there any way to convert a parameter pack of types to a parameter pack of integers from 0 to sizeof...(Types)? More specifically, I'm trying to do something this this:

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

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

For example, foo<int,float,double>() should call bar<0, 1, 2>();

In my use case the parameter pack Types may contain the same type multiple times, so I cannot search the pack to compute the index for a given type.


回答1:


In C++14 you can use std::index_sequence_for from the <utility> header along with tagged dispatch. This is known as the indices trick:

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

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

If you are limited to C++11, you can find many implementations of the above online, such as this one.



来源:https://stackoverflow.com/questions/31054068/c-convert-a-parameter-pack-of-types-to-parameter-pack-of-indices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!