Std :: foreach with boost :: bind

What is 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.

+3
source share
3 answers

You need to use boost::refto pass the argument / object via the link, otherwise bind creates an internal copy.

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

Please note that while the Cat Plus Plus solution will work for you, it is recommended to use such things in C ++ 03 (until lambdas is in the upcoming standard version), use standard library algorithms and functors. Unfortunately, in some cases they are quite confusing, but in this case I think they give a clearer code:

std::copy(second.begin(), second.end(), std::back_inserter(first));
+6
source
std::list<T> ls;
std::list<T> ls0;
// ...
ls.insert(ls.end(), ls0.begin(), ls0.end());
+3

All Articles