Is it valid to have a comparator taking parameters of different type?

J

Juha Nieminen

Is it valid to use, for example, std::equal_range() with a comparator
taking parameters of different type?

It compiles and works correctly at least with gcc and MSVC++, but
AFAIK at least in some versions of the latter, if you turn enough checks
on, it will give an error because the parameter types are not the same.

What does the standard say about this?

Example code:

//----------------------------------------------------------------
struct A
{
int value;
A(int v=0): value(v) {}
};

struct B
{
int value;
B(int v=0): value(v) {}
};

struct Comparator
{
bool operator()(const A& a, const B& b) const
{ return a.value < b.value; }

bool operator()(const B& b, const A& a) const
{ return b.value < a.value; }
};

#include <algorithm>
#include <iostream>

int main()
{
A table[1000];
for(int i = 0; i < 1000; ++i) table = i/10;

B element(25);
std::pair<A*, A*> range =
std::equal_range(table, table+1000, element, Comparator());

std::cout << "Range for value " << element.value
<< " starts at position " << range.first - table
<< " and is " << range.second - range.first
<< " elements long.\n";
}
//----------------------------------------------------------------
 
J

Juha Nieminen

Victor said:
Absolutely. The type of the "value" to which your comparator compares
the objects referenced to by the iterators is the second, independent,
type argument of the 'equal_range' template. What book on the Standard
library are you reading that doesn't explain that?

I know that the iterator template parameter and the value template
parameter are not forced to be related to the same type, and that
because of how a function like std::equal_range has been implemented, it
compiles and works like a marvel.

However, does the C++ standard guarantee that an algorithm like
std::equal_range must always work correctly even if the iterators and
the value (and thus also the comparator) refer to completely unrelated
types, as long as the comparator has been implemented properly to accept
these two different types?

Why does MSVC++ complain about this when enough concept checks have
been turned on? Is it a compiler bug?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top