如何从元组中获得第n个类型

How to get N-th type from a tuple?

本文关键字:类型 元组      更新时间:2023-10-16

我想做一个模板,我可以输入一个索引,它会给我在该索引的类型。我知道我可以用decltype(std::get<N>(tup))做这个,但我想自己实现它。例如,我想这样做,

typename get<N, std::tuple<int, bool, std::string>>::type;

…它会给我位置N - 1的类型(因为数组从0开始索引)我怎么做呢?谢谢。

这种特性已经存在,它被称为std::tuple_element

下面是一个的实例来演示它的用法。

#include <tuple>
#include <type_traits>
int main()
{
    using my_tuple = std::tuple<int, bool, char>;
    static_assert(std::is_same<std::tuple_element<0, my_tuple>::type, int>::value, "!");
    static_assert(std::is_same<std::tuple_element<1, my_tuple>::type, bool>::value, "!");
    static_assert(std::is_same<std::tuple_element<2, my_tuple>::type, char>::value, "!");
}

您可以使用类模板和部分专门化来做您想做的事情。(注意,std::tuple_element几乎与另一个答案相同):

#include <tuple>
#include <type_traits>
template <int N, typename... Ts>
struct get;
template <int N, typename T, typename... Ts>
struct get<N, std::tuple<T, Ts...>>
{
    using type = typename get<N - 1, std::tuple<Ts...>>::type;
};
template <typename T, typename... Ts>
struct get<0, std::tuple<T, Ts...>>
{
    using type = T;
};
int main()
{
    using var = std::tuple<int, bool, std::string>;
    using type = get<2, var>::type;
    static_assert(std::is_same<type, std::string>::value, ""); // works
}