Search code examples
c++stlboost-bind

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.


Solution

  • You need to use boost::ref to pass an argument/object via reference, otherwise bind creates an internal copy.

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