Operator overloading - error: too many parameters for this operator function

Dear cplusplus forum members,
when trying to overload the operator < with a non-member function, I get an error such as 'error: too many parameters for this operator function' :

1
2
3
4
5
6
7
8
9
10
11
12
      struct MyClass
      {
            const Alfa alfa;
            const Beta beta;
            const Gamma gamma;
      };

      // To order the keys in the map
      inline bool operator< (const MyClass& a, const MyClass& b)
      {
         // ...
      }


Looking into internet (for instance http://stackoverflow.com/questions/19709048/c-overloading-operator-for-struct-error-too-many-parameters ) they report it depends by the compiler confusing the operator for an instance method and appending the third implicit parameter (this).
Adding a friend modifier to the function declaration solves the problem, since friend is not allowed to instance methods.


But what is the rationale behind? I mean, the class is already defined, there is no operator< declared, why can the compiler confuse it for an instance method?

Kind regards,
Dean
I don't see a reason why this should fail if lines 9-12 are not within the MyClass definition. I wonder what would happen if you removed the inline keyword. This causes very specific compile-time things to happen.

Edit: I wouldn't consider this a begginer question so +1 for underestimating yourself.
Last edited on
My compiler works without adding the friend keyword. (I just copied your code to see if the compiler would scream).

Can you give me an example on where you defined it and where you use it?

EDIT: I do believe like Stewbond, that the inline keyword is messing up with your compile units.

RE-EDIT: I suppose that within your operator overload you call the other relational operators for the following struct/classes: Alfa, Beta, Gamma. Did you create member operators for those struct/classes with the appropriate number of parameters?... I think that's why it is messing with you :)
Last edited on
Hi there,
SeiZa thanks for having tried the sample code, you are right! And I am an ape!:)
I extrapolated that piece from some mess, only now I am becoming aware I am inside a class definition, opened somewhere above the error.
The compiler believes the operator is defined for the outer class.

Kind regards,
Dean
Easy way to remember where is the scope of relational operators:

2 args = global scope
1 arg = class/struct member scope

If one of them pops up an error... you HAVE to check the call stack :)
Topic archived. No new replies allowed.