c++ - 嵌套绑定(bind)到成员,需要一个指针,得到一个引用。做什么?

标签 c++ visual-studio-2010 c++11 bind unique-ptr

我有一个 foo 类型的 std::unique_ptr 映射,我正在尝试迭代该映射,将每个映射的值传递给不在映射中的 foo 的公共(public)成员。我很接近,但我无法弄清楚如何将最内层绑定(bind)的结果从引用转换为指针。

给定:

class foo
{
public:
    bool DoWork(foo *);
};

std::map<long, std::unique_ptr<foo> map_t;

map_t foo_map_;
foo bar_;

std::for_each(std::begin(foo_map_), std::end(foo_map_), std::bind(&Foo::DoWork, &bar_, std::bind(&std::unique_ptr<foo>::get, /* This guy here -->*/std::bind(&std::pair<long, std::unique_ptr<foo>>::second, std::placeholders::_1))));

建议?我正在使用 Visual Studio 2010 SP1。

最佳答案

编译器错误是由于std::map const'ifies 键类型,所以 value_typemap_t不是 std::pair<long, std::unique_ptr<foo> >而是std::pair<long const, std::unique_ptr<foo> > .为避免此类错误,最好使用 map_t::value_type .以下更改修复了错误:

... std::bind(&map_t::value_type::second, std::placeholders::_1) ...

在 C++11 中,您可以将其简化为:

for(auto const& kv : foo_map_)
    bar_.DoWork(&*kv.second);

或者,使用 std::for_each和 C++11 lambda:

for_each(foo_map_.begin(), foo_map_.end(), 
    [&bar_](map_t::value_type const& kv) { bar_.DoWork(&*kv.second); });

关于c++ - 嵌套绑定(bind)到成员,需要一个指针,得到一个引用。做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11529504/

相关文章:

c++ - ZeroMQ PGM Multicast 不支持来自应用层的回复处理?

c# - Visual Studio - Debug模式下的性能对比安装的应用程序

visual-studio-2010 - 在 Visual Studio 2010 上手动安装 ".nupkg"包

c++ - 从 C++ 文本文件中读取复数 (a+bi)

c++ - 将可变数量的数组引用传递给具有可变参数模板的函数

c++ - 线程间的信号

c++ - 如何设计一个最近最近使用的缓存?

被类函数隐藏的 C++ 友元函数?

visual-studio - 解决冲突后在TFS中强制合并

c++ - 重载 boost::lexical_cast 函数