2012-02-26 96 views
2

以下两种情况有什么区别?boost :: bind与地图绑定,绑定std :: pair和std :: map :: value_type有什么区别?

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); 

第一个示例工作正常,但第二个示例在绑定完成时无法编译。我已经看了看文件stl_map.hvalue_type定义如下:

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

我看不出区别。我希望有人能告诉我,让我知道第二个例子不能编译的原因。

编译错误信息是:提前

.../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 

谢谢!

回答

1

mapvalue_typeconst键(const int你的情况),而您使用的对不(在你的情况下,纯int)。

+0

没错!我没有意识到'const' Gracias! – user1192525 2012-02-26 17:08:52

2

区别在于地图值类型中使用conststd::pair<int,std::string>::first不适用于std::pair<const int,std::string>::first。是的,有一对从const版本到非const版本的隐式转换,但是为了调用这样的成员函数,不考虑该转换。 pair的这些用法可能看起来很相似,但实际上它们是完全独立的类,它们在字段位置等方面可能相互无关。

从本质上说,you'e要求推动建立像

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

这是不合法的代码。

+0

是的,我没有意识到'const'需要更多的咖啡。谢谢! – user1192525 2012-02-26 17:11:38

相关问题