c++ - For_each 和指向成员函数的指针

标签 c++ stl

我遇到了以下代码的问题:

#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/

相关文章:

c++ - 从模板函数返回迭代器到 STL 容器

c++ - 表达式 SFINAE : how to select template version based on whether type contains a function with one or more arguments

c++ - 如何 boost Boost ASIO、UDP 客户端应用程序的吞吐量

c++ - 为什么我看到 vector 的大小为零?

具有相同键类型和不同项目类型的c++映射

c++ - STL分配器复制构造函数要求的目的是什么

c++ - 如何为搜索应用程序找到正确的数据结构?

c++ - 工具提示中的 Qt WIdget

c++ - 使用 boost 属性树解析 XML

c++ - 在 std::vector 上调整大小不调用 move 构造函数