Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 462
Matthew Fioravante Avatar asked Jun 25 '15 15:06

Matthew Fioravante


1 Answers

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.

like image 116
TartanLlama Avatar answered Oct 14 '22 07:10

TartanLlama