std::foreach with boost::bind

std::foreach with boost::bind

本文关键字:bind boost foreach std with      更新时间:2023-10-16

这有什么问题:

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());