无法使用客户比较函数构造std :: map?

无法使用客户比较函数构造std :: map?

问题描述:

#include <map> 
using namespace std; 

class C { 
public: 
    C(map<int,int> m) { } 
    int operator()(int a, int b) { 
     return a < b; 
    } 
}; 

int main() {  
    map<int, int> m; 
    map<int, int, C> mymap(C(m)); 
    mymap.insert(pair<int,int>(1,1)); 
} 

为什么我会收到以下错误?:无法使用客户比较函数构造std :: map?

main.cpp: In function 'int main()': 
main.cpp:16:11: error: request for member 'insert' in 'mymap', which is of non-class type 'std::map<int, int, C>(C)' 
mymap.insert(pair<int,int>(1,1)); 

这里是coliru链接:http://coliru.stacked-crooked.com/a/0413a35d3177ef48

+0

这是1小时内的第二个MVP问题 – 2014-11-06 13:07:17

+0

@LightnessRacesinOrbit什么是MVP? – 2014-11-06 13:46:11

+0

@NeilKirk:http://en.wikipedia.org/wiki/Most_vexing_parse – 2014-11-06 13:56:58

这是一个让人头疼的解析的一个例子 - 函数声明,在你期望的目的。

试试这个:

map<int, int, C> mymap((C(m))); 

map<int, int, C> mymap(C(m)); 

在这种mymap中作为一个功能。将其更改为

map<int, int, C> mymap((C(m))); 
+0

但是m在这里是一个对象,而不是一个类型。为什么编译器不明显? – 2014-11-07 14:35:01

+0

你可以在谷歌的“最烦人的解析”在C + +。有很多文章。 – ravi 2014-11-07 14:36:35

在C++ 11也可避免棘手的解析用括号初始化:

map<int, int, C> mymap(C{m}); 

(不过,如果将不同的表现,如果C有一个构造函数C(std::initializer_list<T>)其中map<int, int>将被隐式可转换为T,这样构造函数会被调用)

更新:正如Benjamin Bannier指出的,你可以在任何地方使用括号初始化器:

map<int, int, C> mymap{C{m}}; 

map<int, int, C> mymap{C(m)}; 

在相同的预防措施:C不应该有operator std::pair<const int, int>()

+0

为什么只使用它来构建'C',而不是地图? – 2014-11-06 13:29:55

+0

@BenjaminBannier谢谢,我更新了答案。 – 2014-11-06 13:50:35