這裏有一些代碼對元組進行線性搜索,找到第一個類型U,並且在找不到U時會給出編譯時錯誤。請注意,如果元組包含多個U,它只會找到第一個一。不知道這是否是你想要的政策。它將編譯時索引返回到第一個U的元組。也許你可以用它作爲你的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';
}
C++ 14,因此一些標準庫的實現提供'的std ::得到>(m_storage)'。你應該檢查並看看你的是否有這個功能,讓事情變得非常簡單。 –
2015-01-08 21:42:53