Question

While reading the book "Notes On Programming" by Alexander Stepanov, I encountered the following problems(Page-07) mentioned by him. Its about the less than(<) operator for any type T.

  • Explain why this is wrong for any class T ?
template<typename T>
bool operator<(const T& x, const T& y) {
  return true;
}
  • Explain what are the requirements on T that makes this definition legitimate?
template<typename T>
bool operator<(const T& x, const T& y) {
  return false;
}

I am not able to understand what could be the type of T for which above code works fine. So far I thought(2nd point) that following types(pointers) might legitimate. I know it does not make much sense(not good idea to compare pointer type) and this too depends on the which order object has been created.

class test { };
test x;
test y;
// &x = 0x7fffffffe0bd, &y = 0x7fffffffe0be
bool out = &y < &x;
//out = 0;

Am I missing something obvious here?. Could someone explain about the both scenario?.

Was it helpful?

Solution

Explain what are the requirements on T that makes this definition legitimate?

template<typename T>
bool operator<(const T& x, const T& y) {
  return false;
}

Any type whose instances are all considered to be "equal".

a < b; // false
b < a; // false

The above is perfectly fine for a == b. So, for consistency, if T had an operator==, it should always return true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top