+= on a vector without boost

前端 未结 2 1714
后悔当初
后悔当初 2021-01-22 11:34

Is there any way to use the += operator with a vector without using boost or using a derivated class?

Eg.

somevector += 1, 2, 3, 4, 5, 6, 7;
2条回答
  •  春和景丽
    2021-01-22 12:26

    With a little ugly operator overloading, this isn't too difficult to accomplish. This solution could easily be made more generic, but it should serve as an adequate example.

    #include 
    

    Your desired syntax uses two operators: the += operator and the , operator. First, we need to create a wrapper class that allows us to apply the , operator to push an element onto the back of a vector:

    template 
    struct push_back_wrapper
    {
        explicit push_back_wrapper(std::vector& v) : v_(&v) { }
    
        push_back_wrapper& operator,(const T& x)
        {
            v_->push_back(x);
            return *this;
        }
    
        std::vector* v_;
    };
    

    Then, in order to use this in conjunction with += on a vector, we overload the += operator for a vector. We return a push_back_wrapper instance so that we can chain push backs with the comma operator:

    template 
    push_back_wrapper operator+=(std::vector& v, const U& x)
    {
        v.push_back(x);
        return push_back_wrapper(v);
    }
    

    Now we can write the code you have in your example:

    int main()
    {
        std::vector v;
        v += 1, 2, 3, 4, 5, 6, 7;
    }
    

    The v += 1 will call our operator+= overload, which will return an instance of the push_back_wrapper. The comma operator is then applied for each of the subsequent elements in the "list."

提交回复
热议问题