问题描述
是否有任何方法将类型的参数包转换为整数的参数包从 0
到 sizeof ...(Types)
?更具体地说,我试图这样做:
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>...>();
}
例如, foo< int,float,double> ;()
应该调用 bar< 0,1,2>()
;
在我的使用情况下,参数包 Types
可能包含相同的类型多次,所以我不能搜索包计算给定类型的索引。
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.
推荐答案
在C ++ 14中,你可以使用 std :: index_sequence_for
$ c>< utility> 标题以及标记分发。这被称为 indices trick :
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...>{});
}
如果你只能使用C ++ 11,上面的在线,如。
If you are limited to C++11, you can find many implementations of the above online, such as this one.
这篇关于C ++将类型的参数包转换为索引的参数包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!