2

What's the difference between the following two cases?

std::pair<int,std::string> example_1 (std::make_pair (1,"foo"));
int value_1 = boost::bind (&std::pair<int,std::string>::first,_1) (example_1);

std::map<int,std::string>::value_type example_2 (std::make_pair (2,"boo"));
int value_2 = boost::bind (&std::pair<int,std::string>::first,_1) (example_2);

The first example works fine but the second does not compile when the binding is done. I have looked at the file stl_map.h and value_type is defined as follows:

typedef std::pair<const _Key, _Tp> value_type;

I don't see the difference. I would appreciate is someone can tell let me know and the reason why the second example does not compile.

The compilation error message is:

.../include/boost/bind/mem_fn.hpp:333:36: error: no matching function for call to ‘get_pointer(const std::pair<const int, std::basic_string<char> >&)’
make: *** [main.o] Error 1

Thanks in advance!

user1192525
  • 657
  • 4
  • 20

2 Answers2

2

The difference is the use of const in the map value type. std::pair<int,std::string>::first is not an accessible item on std::pair<const int,std::string>::first. Yes, there's an implicit conversion defined by pair from the const version to the non-const version, but that conversion isn't considered for the purposes of calling a member function like this. Those uses of pair might look similar, but really they are completely independent classes that are unrelated to each other in terms of where field locations and such might go.

In essence, you'e asked boost to build code like

std::pair<const int,std::string> example(3, "Hello");
example.std::pair<int,std::string>::first

which is not valid.

Billy ONeal
  • 104,103
  • 58
  • 317
  • 552
1

map's value_type has a const key (const int in your case), whereas the pair you're using doesn't (plain int in your case).

Pablo
  • 8,644
  • 2
  • 39
  • 29