How to get N-th type from a tuple?

前端 未结 2 1690
慢半拍i
慢半拍i 2020-12-16 12:40

I want to make a template where I can input an index and it will give me the type at that index. I know I can do this with decltype(std::get(tup)) but

相关标签:
2条回答
  • 2020-12-16 13:11

    You can use a class template and partial specializations to do what you want. (Note that std::tuple_element does almost the same like the other answer says):

    #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
    }
    
    0 讨论(0)
  • 2020-12-16 13:28

    That trait already exists, and it is called std::tuple_element.

    Here is a live example that demonstrates its usage.

    0 讨论(0)
提交回复
热议问题