2

I had encountered this question in a test and am not sure why exactly does it produce an error.

#include <iostream>
#include <string.h>
using namespace std;

template<typename T>
T Min(T a, T b)
{
    if (a <= b)
        return a;
    else
        return b;
}

class A
{
public:
    int n;
    A(int n = 0) : n(n) {}
};

int main()
{
    A a1(2), a2(1);
    cout << Min(a1, a2).n;
    return 0;
}

I tried typing it out and running it and one of error messages was this.

error: no match for 'operator<=' (operand types are 'A' and 'A')

Why is that so? Would appreciate if anyone could explain, thanks!

JeJo
  • 30,635
  • 6
  • 49
  • 88
C.P.
  • 39
  • 1

2 Answers2

3

The A is a user-defined type, and hence you need to define the relational operators for comparing its objects.

For instance

bool operator< (const A& lhs, const A& rhs) { return lhs.n < rhs.n; }
bool operator> (const A& lhs, const A& rhs) { return rhs < lhs; }
bool operator<=(const A& lhs, const A& rhs) { return !(lhs > rhs); }
JeJo
  • 30,635
  • 6
  • 49
  • 88
2

Because class A has no operator for comparison, you probably meant to do this:

if(a.n <= b.n)

Alternatively, define the missing operator to make it work:

bool operator<=(A const& a, A const& b)
{
    return a.n <= b.n;
}
Andreas DM
  • 10,685
  • 6
  • 35
  • 62