-2
typedef std::map<int, std::string> mapType;

int main()
{
    mapType aMap;
    aMap[12] = "What the...";
    aMap[10] = "Tell me why";
    aMap[22] = "See you tomorrow";

    std::cout << "What's wrong with the following expression? " << '\n';

    using namespace boost::lambda;
    std::for_each(aMap.begin(), aMap.end(),
                std::cout << "key="
                      << bind(&mapType::value_type::first, _1)
                      << ", value="
                      << bind(&mapType::value_type::second, _1) << "\n");
    return 0;
}

Compile this code, I get message like below:

../main.cpp:28:31: error: cannot bind 'std::basic_ostream' lvalue to >'std::basic_ostream&&' std::cout << "key=" ^ /usr/include/c++/4.8/ostream:602:5: error: initializing argument 1 of >'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, >_Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits; _Tp = >std::_Bind > ::*>(boost::lambda::lambda_functor >)>]' operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)

I don't know what's the problem with it, I just copy the example from the book. Could anyone help me?

I found another problem, seems it's the same with this one. boost::lambda std::map

JeromeCui
  • 39
  • 6

2 Answers2

0

The bind you are using is std::bind(see error message, and it is ADL that causes it finding std::bind first) which doesn't work with this kind of lambda expression.

Use boost::lambda::bind would solve the issue.

#include <boost/lambda/bind.hpp>

and,

boost::lambda::bind(&mapType::value_type::first, boost::lambda::_1)
qduyang
  • 353
  • 1
  • 8
0

Given the && in the error message, your compiler apparently implements (at least a substantial part of) C++11.

That being the case, it's undoubtedly much easier to skip using Boost Bind, and just use a lambda or a range-based for loop.

for (auto const &m : aMap)
    std::cout << "Key = " << m.first << ", value = " << m.second << "\n";

Even without that, for_each with Bind and company is really the wrong way to go. Using pure C++03, I'd do more like:

typedef std::pair<int, std::string> pt;

std::ostream &operator<<(std::ostream &os, pt const &p) { 
    return os << "Key = " << p.first << ", Value = " << p.second;
}

// ...

std::copy(aMap.begin(), aMap.end(), std::ostream_iterator<pt>(std::cout, "\n'));
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111