2016-03-02 44 views
0

是否有一個原因,我無法通過比較仿函數的map構造函數參數:地圖比較構造函數的參數

map<int, string, greater<int>> foo; 
//map<int, string> foo(greater<int>()); Doesn't work 

或者爲什麼我不能沒有提供我自己的比較式傳遞一個拉姆達:

map<int, string, function<bool(const int&, const int&)>> bar([](const int& lhs, const int& rhs){ return lhs > rhs; }); 
//map<int, string> bar([](const int& lhs, const int& rhs){ return lhs > rhs; }); Doesn't work 

我想只能聲明map<int, string>並用比較器構造它。爲什麼我不能?

[Live Example]

+0

因爲這會涉及一些類型擦除,這不是最佳的? –

+0

可能的重複:[爲什麼不從構造函數推斷模板參數?](http://stackoverflow.com/questions/984394/why-not-infer-template-parameter-from-constructor) – NathanOliver

+0

@PiotrSkotnicki你在說,對於函子的版本?但是'map'沒有提供比較構造函數? http://www.cplusplus.com/reference/map/map/map/是不是這到底是什麼? –

回答

1

這個問題從一個誤解莖。要清除起來:

仿函數對象功能

嘗試指派一個函數指針或拉姆達一個對象沒有任何意義。因此,這不能做: map<int, string> bar([](const int& lhs, const int& rhs){ return lhs > rhs; }); 的方式來定義一個map這需要一個函數指針或lambda是使用模板參數從這樣一個問題:map<int, string, function<bool(const int&, const int&)>>

兩個不周選項之間中途的問題是另一個誤解: map<int, string, [](const int& lhs, const int& rhs){ return lhs > rhs; }> 不起作用,因爲比較器模板參數是類型的成員map,而不是的初始值。 因此,使用函數指針或lambda比較器的map必須始終將該值傳遞給構造函數mapmap<int, string, function<bool(const int&, const int&)>> bar([](const int& lhs, const int& rhs){ return lhs > rhs; })否則function<bool(const int&, const int&)>()將用於map中的比較。

這現在可能已經很清楚了,但由於仿函數是對象,所以無法傳遞不相關的對象是完全不同類型的對象的構造值。調用 map<int, string> foo(greater<int>()) 就像是調用 less<int> foo = greater<int> map其比較器模板參數是一個函子的唯一可接受的compatator構造函數參數是可以轉換爲模板參數中函子類型的對象的東西:map<int, string, greater<int>> foo(greater<int>{})這顯然是不必要的,因爲如果沒有提供參數, greater<int>是默認構造的map會導致相同的成員初始化,所以map<int, string, greater<int>>是足夠的。

+1

'map > foo(更大())'是函數聲明(最令人頭痛的解析) –

+0

@PiotrSkotnicki呃,謝謝。很明顯,我沒有嘗試過,因爲這沒什麼意義。我編輯過,並且實際測試了它現在的作用:http://ideone.com/1Ygrze –