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)