这里有一些代码对元组进行线性搜索,找到第一个类型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