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

后端 未结 3 1432
梦如初夏
梦如初夏 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:38

    1. Is this restriction part of the language specification?

    Yes, it is. Why? Well, the main reason is probably because redefining the usual operators for standard types is seen as obfuscating. Imagin overloading operator+(int,int) or operator+(int,char*). That would change the meaning of existing code!

    You could argue that there are operators between standard types that are not defined, so you could safely override them, for example operator*(char*,int), but that is usually seen as rather useless.

    Moreover, operator overloads must be global, (or be in the namespace of some of its members (argument dependent lookup), but with standard types there are no namespace to depend on), so interoperatibility between libraries that fancy to override them would be a nightmare.

    1. "hello" + "world": why doesn't the compiler convert the two char* "s to two strings?

    Well, for one, std::operator+(const std::string&, const std::string&) is in namespace std; so it will not be found by default.

    You could try calling the operator explicitly: std::operator+("hello", "world"), but alas, there are so many operator+() overloads, many of them templates, that the call is ambiguous.

    So, taking all this into account, I think that a reasonable requirement is that at least one of the operators to be of a user-defined type. Think about it: the global and namespace problem is solved, ADL can be used (actually it was invented for this use) and it is impossible to redefine an operator with an existing meaning (except operator,() and operator&(), I think, but who wants to override these...).

提交回复
热议问题