本文介紹了獲取元組元素類型的索引?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
如果我有一個具有不同元素類型的元組,例如
If I have a tuple with different element types like
std::tuple<T0, T1, T2, ...>
以及如何獲取元素類型的索引?
And how to get the index of a element type?
template<class T, class Tuple>
struct Index
{
enum {value = ?;}
};
謝謝.
推薦答案
template <class T, class Tuple>
struct Index;
template <class T, class... Types>
struct Index<T, std::tuple<T, Types...>> {
static const std::size_t value = 0;
};
template <class T, class U, class... Types>
struct Index<T, std::tuple<U, Types...>> {
static const std::size_t value = 1 + Index<T, std::tuple<Types...>>::value;
};
在 Coli 現場觀看.
See it live at Coliru.
此實現返回給定類型第一次出現的索引.請求不在元組中的類型的索引會導致編譯錯誤(并且相當難看).
This implementation returns the index of the first occurrence of a given type. Asking for the index of a type that is not in the tuple results in a compile error (and a fairly ugly one at that).
這篇關于獲取元組元素類型的索引?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!