这里有一些代码可以对元组进行线性搜索以找到它找到的第一个类型 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';
}