我遇到了以下代码的问题:
#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)); // this placeholder is not a pointer so it can't work anyways
// I also tried something with lambdas like this but it 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));
// it doesn't even work that way
//for_each(l.begin(), l.end(), bind([](Person& p, ostream& out) { p.print(out); }, std::placeholders::_1, cout));
}
这是一条错误消息(在所有情况下)
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>>'
我想知道引擎盖下的内容以及它为什么不起作用。它在谈论什么 protected 成员?
最佳答案
您的 for_each
调用(以及关联的 bind
)正在尝试复制 std::cout
(不管 print
本身需要引用)这是不可能的,因为流是不可复制的。
在 C++03 中,强制其不可复制性的唯一方法是将其复制构造函数声明为 protected
(或 private
),因此出现错误重新看到。
通过 std::ref
(std::cout)
代替。
关于c++ - For_each 和指向成员函数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30560229/