2

I was trying to define a unary operator+ for a certain type. I was hoping this operator could be used only within the scope of a class, but even if that's not possible, I'm still confused by this:

struct X {};

struct Foo {
    friend const char* operator+(X x) { return "hi"; }

    void foo() {
        +X{};   // error: invalid argument type 'X' to unary expression
    }
};
int main() {
    +X{};   // error: invalid argument type 'X' to unary expression
    return 0;
}

If the operator isn't callable inside the class, and it's not callable outside the class, is it callable at all? Where did it go?

(Note that +(X{}) behaves the same way, and if the operator+ is moved outside of struct Foo, both calls are valid.)

jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • It may be helpful if you also include a snippet demonstrating the fact that this works if you move the `operator+(X)` to outside of `Foo`, hence the surprise here. Likewise, you may wish to comment that this is not an issue of operator precedence, i.e. `+(X{});` is evaluated the same. – Brian61354270 Mar 04 '20 at 20:28
  • @FredLarson It's a friend function, not a member function. – Brian61354270 Mar 04 '20 at 20:30
  • I also tried `*this + X{}` and that didn't work (as expected). – jtbandes Mar 04 '20 at 20:30
  • Interesting. If you only declare the friend operator within `Foo`, and define it outside of the class definition, the error within `main` is resolved. I wonder if postponing the definition of `Foo:foo` would fix the remaining error. – Brian61354270 Mar 04 '20 at 20:32
  • Yes, because then the friend declaration has no effect at all. You could remove it entirely, and you'd expect everything to work. – jtbandes Mar 04 '20 at 20:33
  • 2
    Duplicate: https://stackoverflow.com/questions/381164/friend-and-inline-method-whats-the-point (note this in the accepted answer: "*It makes the operator not visible to normal lookup*") – Nikos C. Mar 04 '20 at 20:34

0 Answers0