यहां कुछ प्रकार के कोड हैं जो इसे पहले प्रकार यू के लिए एक टुपल की रैखिक खोज करने के लिए करते हैं, और अगर यह यू नहीं मिल पाता है तो संकलन-समय त्रुटि देता है। नोट अगर टुपल में एकाधिक यू है तो यह केवल पहले पाता है एक। सुनिश्चित नहीं है कि वह नीति है जिसे आप चाहते हैं या नहीं। यह संकलन-समय सूचकांक को पहले यू के टुपल में लौटाता है। शायद आप इसे अपने std::get
में इंडेक्स के रूप में उपयोग कर सकते हैं।
अस्वीकरण: इस उत्तर के लिए एक साथ फेंक दिया गया। केवल हल्के ढंग से परीक्षण किया। एक खाली ट्यूपल जैसे एज मामलों में एक ग़लत त्रुटि संदेश होता है जिसे बेहतर किया जा सकता है। आदि
#include <type_traits>
#include <tuple>
template <class Tuple, class T, std::size_t Index = 0>
struct find_first;
template <std::size_t Index, bool Valid>
struct find_first_final_test
: public std::integral_constant<std::size_t, Index>
{
};
template <std::size_t Index>
struct find_first_final_test<Index, false>
{
static_assert(Index == -1, "Type not found in find_first");
};
template <class Head, class T, std::size_t Index>
struct find_first<std::tuple<Head>, T, Index>
: public find_first_final_test<Index, std::is_same<Head, T>::value>
{
};
template <class Head, class ...Rest, class T, std::size_t Index>
struct find_first<std::tuple<Head, Rest...>, T, Index>
: public std::conditional<std::is_same<Head, T>::value,
std::integral_constant<std::size_t, Index>,
find_first<std::tuple<Rest...>, T, Index+1>>::type
{
};
#include <iostream>
int main()
{
typedef std::tuple<char, int, short> T;
std::cout << find_first<T, double>::value << '\n';
}
स्रोत
2011-05-17 14:48:55
सी ++ 14, और इस तरह कुछ मानक पुस्तकालय कार्यान्वयन प्रदान 'std :: मिल <एसटीडी: : वेक्टर> (m_storage) '। आपको जांचना चाहिए और देखना चाहिए कि आपके पास यह सुविधा है या नहीं, चीजों को बहुत आसान बनाता है। –