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

前端 未结 2 1860
梦如初夏
梦如初夏 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条回答
  •  萌比男神i
    2020-12-08 00:53

    Is there any technical reason we couldn't have front_emplacer, back_emplacer, and emplacer?

    No, there is no technical reason. As proof, here is a complete implementation of back_emplacer with a demo of your Use Case 1...

    #include 
    #include 
    #include 
    
    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=(T&& t)
        {
            container->emplace_back(std::forward(t));
            return *this;
        }
    
        back_emplace_iterator& operator*() { return *this; }
        back_emplace_iterator& operator++() { return *this; }
        back_emplace_iterator& operator++(int) { return *this; }
    };
    
    template< class Container >
    inline back_emplace_iterator
    back_emplacer( Container& c )
    {
        return back_emplace_iterator(c);
    }
    
    struct Demo
    {
        int i;
        Demo(int i) : i(i) {}
    };
    
    int main()
    {
        std::vector x = {1,2,3,4,5};
    
        std::vector y;
    
        std::copy(x.begin(), x.end(), back_emplacer(y));
    
        for (auto d : y)
            std::cout << d.i << std::endl;
    }
    

    Possible Known Issue: Does the universal reference of operator= hide an implicitly generated copy/move operator=? If so these need to be explicitly defined in a way that beats the universal reference in overload resolution.

提交回复
热议问题