Benji Mizrahi
Benji Mizrahi

Reputation: 2164

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

Upvotes: 2

Views: 100

Answers (3)

Anton Savin
Anton Savin

Reputation: 41301

In C++11 you can also avoid vexing parse by using brace initializer:

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)

Update: as Benjamin Bannier pointed out, you can use brace initializers everywhere:

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>().

Upvotes: 0

ravi
ravi

Reputation: 10733

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

In this mymap is taken as a function. Change it to

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

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258568

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

Upvotes: 2

Related Questions