Reputation: 8418
My question is in many ways similar to this one: Pass a custom comparator through a function, but I tried the solution proposed there, and could not get it to work.
In a nutshell, I have a method that keeps several sorted structures and performs several comparisons, always on elements of type int
, all using the same ordering. The ordering is determined when the method is called.
The intended call would look something like: myFunction(std::greater<int>());
First, I tried declaring function as: void myFunction(binary_operator<int, int, bool> order);
but, as per this explanation, binary_function
is not suited to act as a base class in function calls.
Finally, I tried the suggestion from this answer (and many other sites), which suggested using templates. But, I still can not get my code to compile.
The minimal non-working example:
template <typename Comparator>
void myFunction(Comparator order){
if (order(1,2)){
// some stuff
// COMPILES OK
}
std::vector <int> vecToSort;
// ... initialize
std::sort(vecToSort.begin(), vecToSort.end(), order); // works
// COMPILES OK
std::multimap <int, int, order > boundary;
// STARTS KICKING, SCREAMING AND SHOUTHING
}
and the compile error I get:
error: type/value mismatch at argument 3 in template parameter list for ‘template class std::multimap’ error: expected a type, got ‘order’
I figured the same trick should work for both. It does not. (edit: I can see the type
/object
problem now)
Can somebody please explain what is happening here and how to get the multimap
to use the ordering passed as the function argument?
PS: I am not using boost for this project.
Upvotes: 0
Views: 3236
Reputation: 56479
Use Comparator
and order
in this form:
std::multimap <int, int, Comparator> boundary (order);
First pass the compare type inside <>
and then pass the compare object in constructor.
Upvotes: 2
Reputation: 158469
It should be declared as follows:
std::multimap <int, int, Comparator> boundary(order);
^^^^^^^^^^
As the comments say, you need to provide a type
not an object
. These docs for Construct multimap give some examples.
Upvotes: 2