Search code examples
c++boost-lambda

Boost.Lambda: Insert into a different data structure


I have a vector that I want to insert into a set. This is one of three different calls (the other two are more complex, involving boost::lambda::if_()), but solving this simple case will help me solve the others.

std::vector<std::string> s_vector;
std::set<std::string> s_set;
std::for_each(s_vector.begin(), s_vector.end(), s_set.insert(boost::lambda::_1));

Unfortunately, this fails with a conversion error message (trying to convert boost::lambda::placeholder1_type to std::string).

So... what's wrong with this?


Solution

  • The error is really nasty, but boils down to the fact that it can't figure out which set::insert to use, since there's three overloads.

    You can work around the ambiguity by giving bind a helpful hand, by specifying a pointer to the function you wish to use:

    typedef std::set<std::string> s_type;
    typedef std::pair<s_type::iterator, bool>(s_type::*insert_fp)(const s_type::value_type&);
    std::for_each(s_vector.begin(), s_vector.end(), boost::bind(static_cast<insert_fp>(&s_type::insert), &s_set, _1));
    

    It's not pretty, but it should work.