2012-02-26 73 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

相關問題