-1
#include <iostream>
#include<vector>
using namespace std;

template <class T> class vector_inserter{
public:
    std::vector<T> v;
    vector_inserter(std::vector<T>& v):v(v){}
    vector_inserter& operator,(const T& val){v.push_back(val);return *this;}
};
template <class T> vector_inserter<T> operator+=(std::vector<T>& v,const T& x)
{
    return vector_inserter<T>(v),x;
}

int main()
{
vector_inserter<int> t+=1,2,3,

}

I came across this code in stack overflow, i am still trying to understand how it works, i try to compile the above code but i get errors as expected initializer be +=

Is there any good way to overload operators for Vector operation like {}, (), +=?

AmithRc
  • 89
  • 6

1 Answers1

0

Boost Assign is one of the few parts of Boost that I really consider mostly obsolete (see Which Boost features overlap with C++11?)

Firstly, here's a (much) more general version of your code fixed:

Live On Coliru

#include <iostream>
#include <vector>
#include <list>
#include <map>

template <class C> struct inserter {
    C& c;
    template <typename T>
    inserter& operator,(const T& val){ c.insert(c.end(), val); return *this; }
};

template <typename C, typename V = typename C::value_type> inserter<C> operator+=(C& c, const V& x) {
    return inserter<C>{c}, x;
}

int main()
{
    std::vector<int> t;
    t += 1,2,3;

    std::list<int> l;
    l += 1,2,3;

    std::map<int, std::string> m;
    m += std::make_pair(1, "one"), std::make_pair(2, "two"), std::make_pair(3, "three");
}

Note how it works for other types.

Here's how you'd write similar things in /just/ c++11:

std::vector<int> t {4,5,6};
t.insert(t.end(), {1,2,3});
t.assign({1,2,3});
sehe
  • 374,641
  • 47
  • 450
  • 633
  • I found easy way. Vector& operator+=(const T &val){t.push_back(val);return *this;} Vector& operator,(const T &val){t.push_back(val);return *this;} – AmithRc Nov 22 '17 at 22:18