本文介紹了獲取元組元素類型的索引?的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
限時(shí)送ChatGPT賬號(hào)..
如果我有一個(gè)具有不同元素類型的元組,例如
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 現(xiàn)場(chǎng)觀看.
See it live at Coliru.
此實(shí)現(xiàn)返回給定類型第一次出現(xiàn)的索引.請(qǐng)求不在元組中的類型的索引會(huì)導(dǎo)致編譯錯(cuò)誤(并且相當(dāng)難看).
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).
這篇關(guān)于獲取元組元素類型的索引?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!