简体   繁体   English

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

[英]Cannot construct an std::map with a customer compare functor?

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

Why do I get the following error?: 为什么会出现以下错误?

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

Here is the coliru link: http://coliru.stacked-crooked.com/a/0413a35d3177ef48 这是coliru链接: http ://coliru.stacked-crooked.com/a/0413a35d3177ef48

This is an example of a vexing parse - function declaration, where you'd expect an object. 这是令人烦恼的解析-函数声明的示例,在该函数中您期望有一个对象。

Try this: 尝试这个:

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

In this mymap is taken as a function. 在此,将mymap作为函数。 Change it to 更改为

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

In C++11 you can also avoid vexing parse by using brace initializer: 在C ++ 11中,您还可以通过使用括号初始化程序避免繁琐的解析:

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

(Though if would behave differently if C had a constructor C(std::initializer_list<T>) where map<int, int> would be implicitly convertible to T , so that constructor would be called instead) (尽管如果C具有构造函数C(std::initializer_list<T>) ,如果行为会有所不同,其中map<int, int>将隐式转换为T ,那么将改为调用构造函数)

Update: as Benjamin Bannier pointed out, you can use brace initializers everywhere: 更新:正如本杰明·班尼尔(Benjamin Bannier)所指出的,您可以在任何地方使用括号初始化器:

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

or 要么

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

With the same precaution: C shouldn't have operator std::pair<const int, int>() . 使用相同的预防措施: C不应具有operator std::pair<const int, int>()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM