我有一个 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_type
的 map_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/