【问题标题】:How to get N-th type from a tuple?如何从元组中获取第 N 种类型?
【发布时间】:2013-05-31 11:43:40
【问题描述】:

我想制作一个模板,我可以在其中输入一个索引,它会给我那个索引的类型。我知道我可以用decltype(std::get<N>(tup)) 做到这一点,但我想自己实现它。比如我想做这个,

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

...它会给我N - 1位置的类型(因为数组从0开始索引)。我怎样才能做到这一点?谢谢。

【问题讨论】:

    标签: c++ templates c++11 stdtuple


    【解决方案1】:

    您可以使用类模板和部分特化来做您想做的事。 (请注意,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
    }
    

    【讨论】:

    • @user1131467 这就是我决定这样做的方式
    【解决方案2】:

    该特征已经存在,它被称为std::tuple_element

    这是一个live example,它演示了它的用法。

    【讨论】:

    • 但我说我想自己实现这个。 :)
    • 鉴于 “我知道我可以做到这一点,但我想自己实现。”,这不是一个答案,而是一个评论(虽然一个有用的,因为OP 似乎不知道std::tuple_element)。
    • @user2030677:对不起,我应该更好地阅读问题的文字 - 我不知何故跳过了那部分:)
    • @ChristianRau:是的,我没有意识到当我写下答案时(我重新阅读了几次问题,我的大脑只是跳过了那部分)
    猜你喜欢
    • 2013-03-11
    • 2021-12-22
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2011-03-19
    • 1970-01-01
    相关资源
    最近更新 更多