C++ Transform a std::tuple to a std::vector or std::deque

前端 未结 2 1576
不思量自难忘°
不思量自难忘° 2021-02-04 15:57

In the simple parser library I am writing, the results of multiple parsers is combined using std::tuple_cat. But when applying a parser that returns the same result

2条回答
  •  执念已碎
    2021-02-04 16:13

    With the introduction of std::apply(), this is very straightforward:

    template >>>
    std::vector to_vector(Tuple&& tuple)
    {
        return std::apply([](auto&&... elems){
            return std::vector{std::forward(elems)...};
        }, std::forward(tuple));
    }
    

    std::apply() is a C++17 function but is implementable in C++14 (see link for possible implementation). As an improvement, you could add either SFINAE or a static_assert that all the types in the Tuple are actually T.


    As T.C. points out, this incurs an extra copy of every element, since std::initializer_list is backed by a const array. That's unfortunate. We win some on not having to do boundary checks on every element, but lose some on the copying. The copying ends up being too expensive, an alternative implementation would be:

    template >>>
    std::vector to_vector(Tuple&& tuple)
    {
        return std::apply([](auto&&... elems) {
            using expander = int[];
    
            std::vector result;
            result.reserve(sizeof...(elems));
            expander{(void(
                result.push_back(std::forward(elems))
                ), 0)...};
            return result;
        }, std::forward(tuple));
    }
    

    See this answer for an explanation of the expander trick. Note that I dropped the leading 0 since we know the pack is non-empty. With C++17, this becomes cleaner with a fold-expression:

        return std::apply([](auto&&... elems) {
            std::vector result;
            result.reserve(sizeof...(elems));
            (result.push_back(std::forward(elems)), ...);
            return result;
        }, std::forward(tuple));
    

    Although still relatively not as nice as the initializer_list constructor. Unfortunate.

提交回复
热议问题