Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add operator<< to std::vector

Tags:

c++

vector

I want to add operator<< to std::vector<string>. This is the operator

std::vector<std::string>& operator<<(std::vector<std::string>& op, std::string str) {
    op.push_back(str);
    return op;
}

Now I can add elements to vector this way:

std::vector<std::string> vec;
vec << "aaa" << "bbb" << "ccc";

But the following code isn’t compiled since cant pass temporary object by reference.

std::vector<std::string>() << "AAA" << "BBB";

How can I change the code to add elements to temporary vectors too?

I have a function which accepts const std::vector<std::string>& argument so I want to pass to it a vector in one line.

like image 729
Ashot Avatar asked Jun 09 '26 21:06

Ashot


2 Answers

You can't. The only way it could be achieved would be if your operator was a member of the vector. (For some reason member functions can be invoked on temporaries).

As a nonmember function though what you're after is impossible

Also it's not a very good idea to overload operators for STL types such as std::vector. I think what you're trying to accomplish is already present in boost assign library. I don't believe you can write it better than they have, so better use boost if you need this.

like image 188
Armen Tsirunyan Avatar answered Jun 12 '26 10:06

Armen Tsirunyan


I haven't actually thought about the consequences of this properly, but it seems you could have an overload for rvalues:

std::vector<std::string> operator<<(std::vector<std::string>&& op, std::string str) {
  op.push_back(std::move(str));
  return op;
}

Yes, it returns by value, but it will be optimized to a move due to §12.8/32:

When the criteria for elision of a copy operation are met or would be met save for the fact that the source object is a function parameter, and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue.

like image 22
Joseph Mansfield Avatar answered Jun 12 '26 10:06

Joseph Mansfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!