get part of std::tuple

前端 未结 7 1218
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 23:09

I have a tuple of unknown size (it\'s template parametr of method)

Is it way to get part of it (I need throw away first element of it)

For example, I have

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 23:51

    A tuple slice operation (that also works for std::array and std::pair) can be defined like this (C++14 required):

    namespace detail
    {
        template 
        constexpr auto slice_impl(Tuple&& t, std::index_sequence)
        {
            return std::forward_as_tuple(
                std::get(std::forward(t))...);
        }
    }
    
    template 
    constexpr auto tuple_slice(Cont&& t)
    {
        static_assert(I2 >= I1, "invalid slice");
        static_assert(std::tuple_size>::value >= I2, 
            "slice index out of bounds");
    
        return detail::slice_impl(std::forward(t),
            std::make_index_sequence{});
    }
    

    And an arbitrary subset of a tuple t can be obtained like so :

    tuple_slice(t); 
    

    Where [I1, I2) is the exclusive range of the subset and the return value is a tuple of either references or values depending on whether the input tuple is an lvalue or an rvalue respectively (a thorough elaboration can be found in my blog).

提交回复
热议问题