简体   繁体   English

使用boost :: bind的std :: foreach

[英]std::foreach with boost::bind

What's wrong with this: 这有什么问题:

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;
}

It compiles fine, but doesn't work. 编译很好,但不起作用。

You need to use boost::ref to pass an argument/object via reference, otherwise bind creates an internal copy. 您需要使用boost::ref通过引用传递参数/对象,否则bind会创建一个内部副本。

std::for_each(
    second.begin(), second.end(),
    boost::bind(&std::list<T>::push_back, boost::ref(first), _1)
);

Note that while Cat Plus Plus's solution would work for you, the encouraged way to do such things in C++03 (before the advent if lambdas in the upcoming standard version) is to use the standard library algorithms and functors. 请注意,虽然Cat Plus Plus的解决方案对您有用,但在C ++ 03中(在即将推出的标准版本中的lambdas出现之前)鼓励使用标准库算法和仿函数的方法。 Unfortunately, in some cases they get quite convoluted themselves, but in this case I think they produce clearer code: 不幸的是,在某些情况下,他们自己变得非常复杂,但在这种情况下,我认为他们产生了更清晰的代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM