Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

c++ - How to get N-th type from a tuple?

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<N>(tup)) but I would like to implement this myself. For example, I would like to do this,

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

...and it will give me the type at position N - 1 (because arrays indexed starting from 0). How can I do this? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...