#C++ operators

21 messages · Page 1 of 1 (latest)

tidal wasp
#

Why can I not use the operator+(a,b) syntax on ints

mental oysterBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

timid gale
#

You can only define operators for overloads containing at least 1 non primative type

#

Oh wait... are you talking about calling the operator?

#

Calling using operator+ isn't syntactic sugar, but an actual function call.
operator+(int, int) isn't a defined function, as operation on primitives are built-in so to speak

cinder anchor
#

I remember that being the case too, but I wasn’t able to find a reference

#

Where would I find that?

timid gale
#

I didn't find a reference, I just tried defining it and got an error

cinder anchor
#

👍

timid gale
#

;compile

int operator+(int, int);
int main() {}
magic pollenBOT
#
Compiler Output
<source>:1:5: error: 'int operator+(int, int)' must have an argument of class or enumerated type
    1 | int operator+(int, int);
      |     ^~~~~~~~
Build failed
cinder anchor
timid gale
#

There we go :D

tidal wasp
#

the cursed code that code have been made ...

cinder anchor
#

Just make a class named Int 😉

tidal wasp
gilded barn
#

;compile

template <typename T>
T operator+(T lhs, T rhs) { return lhs + rhs; }
int main() { return operator+(0, 0); }
magic pollenBOT
#
Compiler Output
<source>: In function 'int main()':
<source>:3:30: error: no matching function for call to 'operator+(int, int)'
    3 | int main() { return operator+(0, 0); }
      |                     ~~~~~~~~~^~~~~~
<source>:2:3: note: candidate: 'template<class T> T operator+(T, T)'
    2 | T operator+(T lhs, T rhs) { return lhs + rhs; }
      |   ^~~~~~~~
<source>:2:3: note:   template argument deduction/substitution failed:
<source>: In substitution of 'template<class T> T operator+(T, T) [with T = int]':
<source>:3:30:   required from here
<source>:2:3: error: 'T operator+(T, T) [with T = int]' must have an argument of class or enumerated type
Build failed
gilded barn
#

awwww

solar galleon
#

!solved