0
votes

I want to overload the operator< for std::pair class.

template <>
bool operator< (const std::pair<int, std::string>& lhs, const std::pair<int, std::string>& rhs) {
    return lhs.first > rhs.first || (!(rhs.first > lhs.first) && lhs.second < rhs.second); 
};

I get the following error: no function template matches function template specialization 'operator<'

I also tried:

template <>
bool std::pair<int, std::string>::operator< (const std::pair<int, std::string>& lhs, const std::pair<int, std::string>& rhs) {
    return lhs.first<rhs.first || (!(rhs.first<lhs.first) && lhs.second<rhs.second); 
};

This time I get the error: overloaded 'operator<' must be a binary operator (has 3 parameters)

How am I supposed to do this?

1
Without the template <> your 1st version should be OK. - πάντα ῥεῖ
The first one should work but you don't need to make it a template - try leaving off the template <> at the beginning - Jerry Jeremiah
A different reason could be (with the template <> specialization), that you forgot to compile your code with the -std=c++11 flag. - πάντα ῥεῖ
The logic behind your overrides is invalid, because it does not establish ordering. Try comparing x={2,"A"} and y={1, "B"}. The results of both x<y and y<x will be true, which means that the overload cannot be used for ordering. - Sergey Kalinichenko
Even if the specialization compiled, you should still prefer overloading with a nontemplate function: gotw.ca/publications/mill17.htm - jhoffman0x

1 Answers

2
votes

What you write is a template specialisation, which assumes that you have previously defined the template.

Like mentioned in the comments, in this case you don't need to make the operator overloading a template, since you have already specialised the pair.