这有什么问题:
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;
}
它编译得很好,但不起作用。
这有什么问题:
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 中(在即将到来的标准版本中出现 if lambdas 之前)鼓励使用的方法是使用标准库算法和仿函数。不幸的是,在某些情况下,它们自己会变得非常复杂,但在这种情况下,我认为它们会产生更清晰的代码:
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());