最终目标如下:我希望能够for_each
与operator<<
. 我意识到我可以使用ostream_iterator
,但我想看看没有它是否可能。
一些示例代码,以便您了解我想要做什么:
#include <algorithm>
#include <iostream>
#include <functional>
#include <vector>
using std::bind;
using std::ref;
using std::placeholders::_1;
using std::for_each;
using std::ostream;
using std::cout;
using std::endl;
using std::vector;
class C {
private:
int x;
public:
C() : x(0) { }
C(int x) : x(x) { }
friend ostream& operator<<(ostream& out, const C& c);
};
ostream& operator<<(ostream& out, const C& c) {
return out << c.x << endl;
}
int main() {
vector<C> v;
v.push_back(C(1));
v.push_back(C());
for_each(v.begin(), v.end(), bind(&ostream::operator<<, ref(cout), _1));
return 0;
}
我没有成功尝试的一件事(上图):
bind(static_cast<ostream& (ostream::*)(ostream&, const C&)>(&ostream::operator<<), ref(cout), _1)