Why no emplacement iterators in C++11 or C++14?

前端 未结 2 1878
梦如初夏
梦如初夏 2020-12-08 00:34

C++98 has front_inserter, back_inserter, and inserter, but there don\'t seem to be any emplacement versions of these in C++11 or draft

2条回答
  •  误落风尘
    2020-12-08 00:54

    Your main use case is already covered by inserter, back_inserter and front_inserter. There is already a value_type && overload of operator= that will move into the container. The only thing emplacer could do over inserter is call explicit constructors.

    Compare the common overloads of container::insert, container::push_back and container::push_front to container::emplace, container::emplace_back and container::emplace_front

    iterator insert( const_iterator pos, const value_type & value );
    iterator insert( const_iterator pos, value_type && value );
    
    template< class... Args > 
    iterator emplace( const_iterator pos, Args&&... args );
    
    void push_back( const value_type & value );
    void push_back( value_type && value );
    
    template< class... Args >
    void emplace_back( Args&&... args );
    
    void push_front( const value_type & value );
    void push_front( value_type && value );
    
    template< class... Args >
    void emplace_front( Args&&... args );
    

    Each of the emplace variants takes a pack of arguments with which to construct the value. operator = takes exactly one argument. You could write an emplacer that took a tuple of arguments.

    template
    class back_emplace_iterator : public std::iterator< std::output_iterator_tag,
                                                       void, void, void, void >
    {
    protected:
        Container* container;
    public:
        typedef Container container_type;
    
        explicit back_emplace_iterator(Container& x) : container(&x) {}
    
        template
        back_emplace_iterator&
        operator=(std::tuple args)
        {
            std::apply(Container::emplace_back, std::tuple_cat(std::tie(*container), std::forward>(args)));
            return *this;
        }
    
        back_emplace_iterator& operator*() { return *this; }
        back_emplace_iterator& operator++() { return *this; }
        back_emplace_iterator& operator++(int) { return *this; }
    };
    

提交回复
热议问题