[英]C++ Convert a parameter pack of types to parameter pack of indices
有沒有辦法將類型的參數包轉換為從0
到sizeof...(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>
標頭中的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,您可以在線找到上述的許多實現,例如此實現 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.