c++ - For_each and pointer to member function -
i came across problem following code:
#include <list> #include <algorithm> #include <string> #include <iostream> #include <functional> using namespace std; struct person { string name; ostream& print(ostream& out) const { return out << name; } }; int main() { person p = { "mark" }; list<person> l; l.push_back(p); for_each(l.begin(), l.end(), bind(&person::print, std::placeholders::_1, std::cout)); // placeholder not pointer can't work anyways // tried lambdas doesn't work either //for_each(l.begin(), l.end(), bind([](person& p, ostream& out) { mem_fun(&person::print)(&p, out); }, std::placeholders::_1, cout)); // doesn't work way //for_each(l.begin(), l.end(), bind([](person& p, ostream& out) { p.print(out); }, std::placeholders::_1, cout)); }
here's error message (in every case)
microsoft visual studio 12.0\vc\include\tuple(80): error c2248: 'std::basic_ostream<char,std::char_traits<char>>::basic_ostream' : cannot access protected member declared in class 'std::basic_ostream<char,std::char_traits<char>>'
i want know what's under hood , why doesn't work. protected member talking about?
your for_each
call (and associated bind
) trying copy std::cout
(regardless print
takes reference) impossible since streams non-copyable.
in c++03, way enforce non-copyability declare copy constructor protected
(or private
), hence error you're seeing.
pass std::ref
(std::cout)
instead.
Comments
Post a Comment