c++ - Function pointer to friend operator overload for use with bind -
the end goal following: want able utilize for_each operator<<. realized can utilize ostream_iterator see if possible without it.
some illustration code can thought of want do:
#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) { homecoming 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)); homecoming 0; } a thing have unsuccessfully tried (above):
bind(static_cast<ostream& (ostream::*)(ostream&, const c&)>(&ostream::operator<<), ref(cout), _1)
you're specifying wrong operator<<; you've specified ostream::operator<<, operator<< free i.e. ::operator<<.
this works in current program:
for_each(v.begin(), v.end(), bind(&::operator<<, ref(cout), _1)); however if add together more free operator<<s fail again, since bind cannot decide operator<< meant. in case have specify through explicit specialization:
for_each(v.begin(), v.end(), bind<ostream&(*)(ostream&, const c&)>(&::operator<<, ref(cout), _1)); equivalently, utilize static_cast<ostream&(*)(ostream&, const c&)>(&::operator<<).
the problem << in std::cout << c either free operator or fellow member operator, , there's no way know priori. ostream_iterator works generating code allows compiler decide how evaluate expression; if utilize lambda or range loop.
c++ c++11 operator-overloading bind function-pointers
No comments:
Post a Comment