添加运算符<<到 std::vector [英] Add operator<< to std::vector
问题描述
我想将 operator<<<
添加到 std::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;
}
现在我可以通过这种方式向 vector 添加元素:
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?
我有一个接受 const std::vector<std::string>&
参数的函数,所以我想在一行中将一个向量传递给它.
I have a function which accepts const std::vector<std::string>&
argument so I want to pass to it a vector in one line.
推荐答案
你不能.可以实现的唯一方法是您的操作员是否是向量的成员.(出于某种原因,可以在临时对象上调用成员函数).
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
此外,重载 STL 类型(例如 std::vector)的运算符也不是一个好主意.我认为你想要完成的事情已经存在于 boost assign>图书馆.我不相信你可以写得比他们更好,所以如果你需要这个,最好使用 boost.
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.
这篇关于添加运算符<<到 std::vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!