std::foreach with boost::bind
std::foreach with boost::bind
这有什么问题:
template <typename T>
std::list<T> & operator+=(std::list<T> & first, std::list<T> const& second)
{
std::for_each(second.begin(), second.end(), boost::bind(&std::list<T>::push_back, first, _1));
return first;
}
它编译正常,但不起作用。
您需要
使用 boost::ref
通过引用传递参数/对象,否则 bind 会创建一个内部副本。
std::for_each(
second.begin(), second.end(),
boost::bind(&std::list<T>::push_back, boost::ref(first), _1)
);
请注意
,虽然 Cat Plus Plus 的解决方案适合您,但在 C++03 中(在即将到来的标准版本中出现 lambda 之前)中,鼓励执行此类操作的方法是使用标准库算法和函子。不幸的是,在某些情况下,它们本身会变得非常复杂,但在这种情况下,我认为它们会产生更清晰的代码:
std::copy(second.begin(), second.end(), std::back_inserter(first));
std::list<T> ls;
std::list<T> ls0;
// ...
ls.insert(ls.end(), ls0.begin(), ls0.end());
相关文章:
- boost::bind()类似的东西,但用于函数调用
- 泛化传递给 boost::bind 的参数
- Boost.Asio:不能使用 std::bind() 来指定回调
- boost::bind函数缓冲区的最大大小
- 自 1.55 以来,boost::bind / boost::function 中的奇怪行为变化
- 使用 boost::bind 进行订阅回调时出错
- 将 std::bind 应用于带有参数 <boost::asio::ip::tcp::socket> 时出错?
- 如何使用 boost::bind 附加参数?
- boost::bind 无法绑定到纯虚拟基类中定义的非静态函数模板成员类型
- 如何正确绑定成员函数与 boost::bind
- 将 boost::function 和 boost::bind 替换为模板
- Boost Asio - boost::bind 导致程序崩溃
- ioService.post(boost::bind(&myFunction, this, attr1, attri2) 不会发布作品
- 我可以使用 boost::bind 来存储不相关的对象吗?
- 在spirit parser Action中,在上下文参数上编译boost :: bind(成员函数)上的错误
- 如何使用 boost::bind 将返回 int 的函数转换为返回布尔值的函数
- boost::bind with member functions(作为boost::asio异步写入处理程序)
- 创建一个 boost::线程 带有 boost::bind() 或不带
- boost::bind & boost::function with partial args
- boost::bind, boost::shared_ptr and inheritance