c++vectordata-structuresoperator-overloadingreturn-by-reference

Overload operator over and over


I've overloaded operator << in my own vector class that will work as follows

int main() {
    my_vector<int> vec;
    vec << 1 << 2 << 3;     // will add elements at end [ 1, 2, 3 ]

    display(vec);
}

This works perfectly fine as I want, but I wanted to make it more efficient I did this

    10 << vec;              // will add element at begin [ 10, 1, 2, 3 ]

But this goes wrong when I do it multiple times like

    20 << 10 << vec;        // this does [ 20480, 1, 2, 3 ];

that first does operation on 20 << 10, then 20480 << vec

I want to process it like [ 20, 10, 1, 2, 3];


Solution

  • One potential solution is to create a proxy object, or even a full-fledged vector object, that aggregates the elements to be inserted.

    The interface would look approximately like:

    vec_front_inserter(20) >> 10 >> my_vec;
    

    Note that I recommend using the extraction operator (>>) to indicate front-insertion, as it reads better to me, but feel free to change back to the insertion operator (<<) if you don't like this.

    Your implementation would require:

    1. Define an operator>>(const my_vector&, my_vector&) to represent front-inserting one vector into another.
    2. Create a proxy vec_front_inserter class that has operator>>(vec_front_inserter&, int) defined, and holds a my_vector internally.
    3. Define a operator>>(const vec_front_inserter&, my_vector&) to insert the elements at the front of my_vector.
    class vec_front_inserter {
    public:
        vec_front_inserter() {}
        vec_front_inserter(int seed) {
            _data.push_front(seed);
        }
    
        friend vec_front_inserter& operator>>(vec_front_inserter& proxy, int value);
        friend my_vector& operator>>(const vec_front_inserter& proxy, my_vector& vec);
    
    private:
        my_vector _data;
    
    };
    
    vec_front_inserter& operator>>(vec_front_inserter& proxy, int value) {
        _data.push_back(value);
    }
    
    my_vector& operator>>(const vec_front_inserter& proxy, my_vector& vec) {
        vec.insert_front(proxy._data);
    }
    
    

    This feels similar to me to string concatenation.

    You can do something like:

    std::string concat = std::string("foo") + "bar" + "biz" + "baz";
    

    But you can't do something like:

    std::string fail = "foo" + "bar" + "biz" + "baz";