why C++ operator overloading requires “having at least one parameter of class type”?

后端 未结 3 1437
梦如初夏
梦如初夏 2021-02-08 00:18

The chapter 14.1 of \"C++ primer 5th edition\" reads,

An operator function must either be a member of a class or have at least one parameter of class typ

3条回答
  •  失恋的感觉
    2021-02-08 00:34

    Is this restriction part of the language specification? If yes, why C++ designers want to do that?

    Yes, it is. Quoting from N3337, §13.5.6 [over.oper]:

    An operator function shall either be a non-static member function or be a non-member function and have at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.

    About the "why" part, because removing this requirement would mean that you could overload operators for builtin types, which already have their operator semantics defined. That's something totally undesiderable.

    For instance, do you think that defining this makes any sense?

    int operator+(int a, int b) { return a - b; }
    

    Does it allow more people to reason about your program when they read your code, or is it just something surprising that effectively breaks your reasoning?

    What happens if we get pointers into the game?

    bool operator==(const char *str1, const char *str2) { 
        return strcmp(str1, str2) == 0;
    }
    

    Would you expect that operator== now dereferences memory? I wouldn't. It's surprising. It goes against what the Standard already says about these operators. It breaks what every C program in the last 25 years behaved like. The language shouldn't let you do this kind of abuses.

提交回复
热议问题