Search code examples
c++operator-overloading

Why non-member and templated operator is syntactically correct but doesn't work in C++


I see that the following is syntactically correct:

#include <iostream>
using namespace std;
template<class T> bool operator<= (const T& left, const T& right)
{
  cout<<"overloaded"<<endl;
  return left<=right;
}


int main()
{
    cout<<(10<=5)<<endl;
    return 0;
}

But it seems that it is never called.


Solution

  • For overloaded operators to be called, at least one operand needs to have class or enumeration type:

    If no operand of an operator in an expression has a type that is a class or an enumeration, the operator is assumed to be a built-in operator and interpreted according to [expr.compound].

    - [over.match.oper] p1

    Your operator<= is valid and would be called if one of the operands was say, of class type, but in 10<=5, both operands are int, i.e. of fundamental type.

    Also note that return left<=right; would result in infinite recursion (in almost all cases) since it would call the overloaded <= operator again.

    Furthermore, it's highly unusual to overload operators in a way that they would be called for standard library types (or attempt to do that for fundamental types). See also Is it allowed to overload operator+ for a standard library type and a built-in type?. You should stick to overloading operators only for your own types, e.g. by making them a hidden friend or member functions, or constraining them properly.