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;
would actually be
somevector.push_back(1);
somevector.push_back(2);
somevector.push_back(3);
etc.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.
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:Then, in order to use this in conjunction with
+=on a vector, we overload the+=operator for a vector. We return apush_back_wrapperinstance so that we can chain push backs with the comma operator:Now we can write the code you have in your example:
The
v += 1will call ouroperator+=overload, which will return an instance of thepush_back_wrapper. The comma operator is then applied for each of the subsequent elements in the “list.”